The ngIf is an Angular 2 Structural Directive, which allows us to Add/Remove DOM Element. It is similar to the ng-if directive of AngularJs. In this Tutorial let us look at the syntax of ngIf. We will show you how to use ngIf using an example code.
In this article
ngIf Syntax
1 2 3 4 5 6 7 8 | <p *ngIf="condition"> condition is true and ngIf is true. </p> <p *ngIf="!condition"> condition is false and ngIf is false. </p> |
The ngIf is attached to a DOM element ( p element in the above example). It is then bound to an expression. The expression is then evaluated by the ngIf directive. If the expression evaluates to false then the entire element is removed from the DOM. If true then the element is inserted into the DOM.
ngIf does not hide the DOM element. It removes the entire element along with its subtree from the DOM. It also removes the corresponding state freeing up the resources attached to the element.
ngIf Example
Component Class
Create a boolean variable showMe in your component class as shown below
1 2 3 | showMe: boolean; |
Template
Copy the following code to the Template
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <div class="row"> Show <input type="checkbox" [(ngModel)] ="showMe"/> </div> <div class='row'> <div *ngIf="showMe"> ShowMe is checked </div> <div *ngIf="!showMe"> ShowMe is unchecked </div> </div> |
Now let us examine the code in detail
1 2 3 | Show <input type="checkbox" [(ngModel)] ="showMe"/> |
This is a simple checkbox bound to showMe variable in the component
1 2 3 4 5 | <div *ngIf="showMe"> ShowMe is checked </div> |
The ngIf directive is attached to the div element. It is then bound to the expression “showMe”. The expression is evaluated and if it is True, then the div element is added to the DOM else it is removed from the DOM.
ngIf in the above code uses a simple Boolean expression. It can also process the compound boolean expressions. Run the example and see it work. You can download the source code from GitHub
Leave a Reply