×
☰ See All Chapters

Angular ngIf Directive

ngIf directive is used to insert elements to the DOM based on condition. ngIf accepts an expression and If expression evaluates to true then corresponding block will be inserted to DOM. Condition need not to be evaluated to boolean value. If it is 0, "", null, undefined, NaN, or boolean false itself then it is considered false. All other values are considered to be true.

Angular ngIf Directive Syntax

<htmlTag *ngIf="expression">

    Elements to insert into DOM

</htmlTag>

Angular ngIf Directive Example

app.component.ts

import { Component } from '@angular/core';

 

@Component({

        selector: 'app-tag',

        template: ` <p *ngIf="5<6">

                                   This will become visible

                        </p>

                        <p *ngIf="5>6">

                                   This will not be inserted into DOM

                        </p>

                        `

})

export class AppComponent {

        num: string='';

}

 

app.module.ts

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

 

@NgModule({

  declarations: [

      AppComponent

  ],

  imports: [

    BrowserModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

index.html

<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8">

  <title>Angular Example</title>

  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="icon" type="image/x-icon" href="favicon.ico">

</head>

<body>

  <app-tag></app-tag>

</body>

</html>

Output

angular-ngif-directive-0
 

Angular ngIf Directive with If-Then-Else

NgIf supports an if-then-else structure similar to that used in JavaScript. The general markup is given as follows:

<htmlTag *ngIf='condition; then trueBlock else falseBlock'></htmlTag >

<ng-template #trueBlock>...</ng-template>

<ng-template #falseBlock>...</ng-template>

As show, templates are attached to ngIf for both true and false cases. If condition evaluated to true then trueBlock template will be inserted into DOM. If condition evaluated to false then falseBlock template will be inserted into DOM.

import { Component } from '@angular/core';

 

@Component({

        selector: 'app-tag',

        template: ` <div *ngIf = '10<20; then trueBlock else falseBlock'></div>

                                <ng-template #trueBlock>

                                        <label>This will be displayed</label>

                                </ng-template>

                                <ng-template #falseBlock>

                                        <label>This will not be inserted into DOM</label>

                                </ng-template>

                                `

})

export class AppComponent {

        num: string='';

}

angular-ngif-directive-1
 

All Chapters
Author