Example For *Ngif Condition In Angular 4

Now, in Angular 4, *Ngif is slightly changed into if and else condition with added advantages. Here, I will explain how to use the *Ngif Condition with then and else in Angular 4.

In order to work with this new *Ngif, you have to update your latest Angular CLI by the following command.

npm install -g @angular/cli

After the installation of your Angular CLI it upgrades to the latest Angular CLI.(Angular 4)

After Angular CLI updates, create the new Project 

ng new Angular4

 

After creating a new project, now we modify our app.component.ts as follow.

  1. import {  
  2.     Component  
  3. } from '@angular/core';  
  4. import {  
  5.     Hero  
  6. } from './hero';  
  7. @Component({  
  8.     selector: 'my-app',  
  9.     template: `  
  10. <h1>{{title}}</h1>  
  11. <h2>My favorite hero is: {{myHero.name}}</h2>  
  12. <p>Heroes:</p>  
  13. <ul>  
  14. <li *ngFor="let hero of heroes">  
  15. {{ hero.name }}  
  16. <div *ngIf="hero.id == 1; then ifcondition else elsecondition"> ... </div>  
  17. <template #ifcondition>If Condion Works!</template>  
  18. <template #elsecondition>Else Condition Works!</template>  
  19. </li>  
  20. </ul>  
  21. <p *ngIf="heroes.length > 3">There are many heroes!</p>  
  22. `  
  23. })  
  24. export class AppComponent {  
  25.     title = 'Tour of Heroes';  
  26.     heroes = [  
  27.         new Hero(1, 'Windstorm'),  
  28.         new Hero(13, 'Bombasto'),  
  29.         new Hero(15, 'Magneta'),  
  30.         new Hero(20, 'Tornado')  
  31.     ];  
  32.     myHero = this.heroes[0];  
  33. }  

Here, I had to check if the condition with Hero Id is equal to 1;  then it will call #ifcondition template otherwise it will bind the #elsecondition template.

Here, I have used ‘my-app’ as my selector. So I changed my index.html as follows,

  1. <!doctype html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <meta charset="utf-8">  
  6.     <title>MyProjectName</title>  
  7.     <base href="/">  
  8.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  9.     <link rel="icon" type="image/x-icon" href="favicon.ico"> </head>  
  10.   
  11. <body>  
  12.     <my-app>Loading...</my-app>  
  13. </body>  
  14.   
  15. </html>   

Now, run the application with the following command.

ng serve

Then, we get the following result.

.

Next Recommended Readings