ANGULAR 8 ngIf directive with examples

The ngIf statement is used to add or remove HTML elements based on given condition.If the condition is true then element is added otherwise the element is removed

ngIf Syntax<

<div *ngIf="condition">
    condition is true and ngIf is true.  
<div>
<div *ngIf="!condition">
    condition is false and ngIf is false.  
<div>

ngIf Directive with else block

<div  *ngIf="condition; else elseBlock">
        displays content when condition is true.
<div>
<ng-template #elseBlock>
        displays content when condition is false.
<ng-template> 

ngif example in angular 8


Scenario: I want to display my pets only when i click 'Show my pets' checkbox


<div class="col-md-5 offset-md-5">
<input type="checkbox" [(ngModel)]="ShowPets"> SHOW MY PETS
<span *ngIf="ShowPets">
<div *ngFor="let pet of listpets" [ngClass]="{
                        'text-primary':pet.petname==='DOG',
                        'text-secondary':pet.petname ==='CAT',
                        'text-success':pet.petname ==='BIRD',
                        'text-danger':pet.petname ==='ELEPHANT',
                        'text-warning':pet.petname ==='DUCK'
                        }" [ngStyle]="{'font-size.px':24, 'font-weight':'bold'}">                
        {{pet.petname}}
            <div>
    <span>
<div>

ngif else example in angular 8


Scenario: I want to highlight or color my pets only when i click 'HIGHLIGHT or COLOR MY PETS' checkbox otherwise all items in the list will be black.


    <div class="col-md-5 offset-md-5">
    <input type="checkbox" [(ngModel)]="ShowPets"> HIGHLIGHT or COLOR MY PETS
    <span *ngIf="ShowPets; else elseshowallanimals">
    <div *ngFor="let pet of listpets" [ngClass]="{
                            'text-primary':pet.petname==='DOG',
                            'color':pet.petname ==='CAT'?'blue':'black',
                            'text-success':pet.petname ==='BIRD',
                            'text-danger':pet.petname ==='DUCK'
                            }" [ngStyle]="{'color':pet.petname ==='CAT'?'blue':'black','font-size.px':24, 'font-weight':'bold'}">
                
            {{pet.petname}}
                <div>
        <span>
    <ng-template #elseshowallanimals>
    <div *ngFor="let pet of listpets" [ngStyle]="{'font-size.px':24, 'font-weight':'bold'}">
        
    {{pet.petname}}
        <div>
        <ng-template>
<div>

Click here to learn sweet ngSwitch Examples