Angular ngIf

Last Updated on May 20, 2022
Angular ngIf

Angular ngIf

In Angular ngIf structural directive allows us to add or remove the HTML element based on some conditions. Just like other programming languages, it provides all kinds of If-Else statements.

Let’s look at code syntax and some code examples of using ngIf.


<p *ngIf="some condition">
    Hide or display based on the condition is true/false
</p>

Let's take a look at the code example.


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

@Component({
    selector: 'app-demoComponent',
    template:  `
            <p *ngIf="bCondition">Conditionally display or hide the paragraph.</p>
        `
    })

export class DemoComponent {

    bCondition = true; //Could be true or false

    constructor(){ 
        //Constructor
    }
}

Based on the bConditon value, the paragraph will be hidden or shown.

Another example with ngIf else.


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

@Component({
    selector: 'app-demoComponent',
    template:  `
            <p *ngIf="bCondition; else elseBlock">Dispalay if bCondtion value is true.</p>

            <ng-template #elseBlock>
                <p>Dispalay if bCondtion value is false.</p>
            </ng-template>
        `
    })

export class DemoComponent {

    bCondition = false; //Could be true or false

    constructor(){ 
        //Constructor
    }
}

In the above code example, the paragraph will be displayed or hidden based on the bCondtion value whether true or false. We always put other kinds of the code block for else statement using <ng-template #ReferenceId>code statement........</ng-template>

Another example with ngIf then else.


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

@Component({
    selector: 'app-demoComponent',
    template:  `
            <p *ngIf="bCondition; then thenBlock else elseBlock">Demo of if then else</p>

            <ng-template #thenBlock>
                <p>Dispalay if bCondtion value is true.</p>
            </ng-template>

            <ng-template #elseBlock>
                <p>Dispalay if bCondtion value is false.</p>
            </ng-template>
        `
    })

export class DemoComponent {

    bCondition = false; //Could be true or false

    constructor(){ 
        //Constructor
    }
}

In the above example, the paragraph will be displayed or hidden based on the condition given. If the condition is true then the then-block template paragraph will be displayed otherwise else-block template paragraph will be displayed.