Conditional Rendering in Angular using *ngIf directive
In this tutorial, we are going to learn about how to render HTML elements conditionally into the dom by using *ngIf
directive.
Conditional rendering
It means we only render the elements into the dom whenever the provided data becomes true.
Angular has a special directive called *ngIf
which helps us to render the elements conditionally
let’s see an example
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
isActive = false;}
<div>
<h1 *ngIf="isActive">You can't see me</h1></div>
In the above code, we have added *ngIf="isActive"
to the h1
element so that it only renders into the dom whenever the isActive
property becomes true.
Else block
We can also extend the *ngIf
directive with else block.
example:
<div>
<!-- notActive is a reference to else -->
<h1 *ngIf="isActive; else notActive">You can't see me</h1> <ng-template #notActive> <h1>You can see me</h1>
</ng-template>
</div>
In this example, we have added an else notActive
to *ngIf
directive and used it inside ng-template
so that whenever the isActive
property is true
the first h1 element will render otherwise the else
block h1 element will render into the dom.
If you are confused to write this long-form of code we also have an alternate syntax to use the else block.
<div>
<h1 *ngIf="isActive">You can't see me</h1>
<h1 *ngIf="!isActive">You can see me</h1></div>