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.
- import {
- Component
- } from '@angular/core';
- import {
- Hero
- } from './hero';
- @Component({
- selector: 'my-app',
- template: `
- <h1>{{title}}</h1>
- <h2>My favorite hero is: {{myHero.name}}</h2>
- <p>Heroes:</p>
- <ul>
- <li *ngFor="let hero of heroes">
- {{ hero.name }}
- <div *ngIf="hero.id == 1; then ifcondition else elsecondition"> ... </div>
- <template #ifcondition>If Condion Works!</template>
- <template #elsecondition>Else Condition Works!</template>
- </li>
- </ul>
- <p *ngIf="heroes.length > 3">There are many heroes!</p>
- `
- })
- export class AppComponent {
- title = 'Tour of Heroes';
- heroes = [
- new Hero(1, 'Windstorm'),
- new Hero(13, 'Bombasto'),
- new Hero(15, 'Magneta'),
- new Hero(20, 'Tornado')
- ];
- myHero = this.heroes[0];
- }
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,
- <!doctype html>
- <html>
-
- <head>
- <meta charset="utf-8">
- <title>MyProjectName</title>
- <base href="/">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel="icon" type="image/x-icon" href="favicon.ico"> </head>
-
- <body>
- <my-app>Loading...</my-app>
- </body>
-
- </html>
Now, run the application with the following command.
ng serve
Then, we get the following result.
.