Wednesday, 29 November 2017

ng if in Angular 4/5

Angular 4/5ng if

Angular 4+ has updated there ng if capabilities, now it is more developer friendly. You can write if, else and then in html directly. Angular 2 ng if and Angular js 1 ng-if are almost same except some syntax changes. Let us check how it is in Angular 4 with some examples.

Angular 2 ng if




<div *ngIf="showSelected">
  <p>Condition Passed!</p>
</div>

<div *ngIf="!showSelected">
  <p>Condition Failed!</p>
</div>


Angular 4/5 ng if




<div *ngIf="showSelected; else hideSelected">
  <p>Condition Passed!</p>
</div>

<ng-template #hideSelected>
  <p>Condition Failed!</p>
</ng-template>


Let us check with another example



<div *ngIf="showSelected; then showTemplate else hideTemplate"></div>

<ng-template #showTemplate>
  <p>Condition Passed!</p>
</ng-template>

<ng-template #hideTemplate>
  <p>Condition Failed!</p>
</ng-template>


You can handle many scenarios like this in html itself and it is one of the great advantage of Angular 4. Let us check with one more scenario for showing loading message. This will be helpful as we need to show loading message for most of the dynamic data which is getting from backend.



<div *ngIf="dataFromServer; else loadingBar">
  <p>{{dataFromServer}}</p>
</div>

<ng-template #loadingBar>
  <p>Loading</p>
</ng-template>


Here loading message will be shown unless dataFromServer has got some values. Let me share component code as well, here I am setting the flag as true or false.

Component


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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  showSelected: boolean;
  dataFromServer: string;

  constructor() {
    this.showSelected = true;
    this.dataFromServer = 'Hello';

  }
}

In this article we have discussed about Angular 4 ng if with many examples.

Angular 4/5ng if

Related Info

1. Http calls in Angular with simple examples.

2. Set header for http request in Angular

3. Angular client side pagination.

4. Angular show more/less pagination

No comments :

Post a Comment