Conditional Directives

Angular Conditional Directives

Angular conditional directives can be applied to controls on the view and the browser will manipulate and display the DOM accordingly. In this chapter, we will go through:

  1. If else
  2. Switch

Let’s create a view,

IllinoisView.html

<ng-template [ngIf]="city === 'Chicago'" [ngIfElse]="NotFound">
    <div>
      <img width="500" alt="No Img" src="../assets/WelcomeToChicago.PNG">
    </div>
  </ng-template>
  
  <ng-template #NotFound>
    <div>
      Image not found in collection.
    </div>
  </ng-template>


  <div [ngSwitch]="county">
    <div *ngSwitchCase="'Chicago'">
      <ul>
        <li>Cook</li>
        <li>DuPage</li>
        <li>DeKalb</li>
      </ul>
    </div>
    <div *ngSwitchCase="'Galena'">
      <ul>
        <li>Jo Davies</li>
      </ul>
    </div>
    <div *ngSwitchDefault>County not found</div>
  </div>

If-Else

We applied if else condition in the <ng-template> above. Please note ng-template is an inbuilt template for angular used to convert it to panel and wont be visible in the DOM. You can apply the conditions on any other controls too.

The panel with image will be display if City = Chicago. Otherwise ‘Image not found in collection’ will be displayed. This is achieved by applying

 [ngIf]=”city === ‘Chicago'” [ngIfElse]=”NotFound”

If City is not Chicago,  [ngIfElse] will display the panel where id = ‘NotFound’

Switch Case

We applied switch case in the example above by specifying [ngSwitch]=”county” and provided cases in below and display the panel as per the satisfying cases *ngSwitchCase=”‘Chicago'”

The code for component is as below.

IllinoisComponent.ts

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

@Component({
  templateUrl: './IllinoisView.html'
})

export class IllinoisComponent 
{
  city = 'Chicago';
  county='Chicago';
}

We applied city = Chicago and county = Chicago hence our conditional directive will display the panel with the image of Chicago and the list items as seen in the UI below

IllinoisComponent.ts

export class IllinoisComponent 
{
  city = 'Chicago';
  county='Ny';
}

The condition to display the list view is not satisfied hence the text ‘County not found’ will be displayed as we applied the switch case in the UI above