The Angular *NgIf
directive is used when we wants to remove/display an elements from the DOM
based on our condition.
If your condition is false [*ngIf='false'] the element the directive is attached to will be
removed from DOM.
What
Are the Difference Between [hidden] = 'false' and *ngIf = 'false'?
The [hidden]
= ‘false’ is used to simply hides the elements but the *ngIf= ‘false’ is used to removes the element completely from the DOM when the condition is not true.
See
the below examples – Used of Angular *NgIf
import {NgModule, Component} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
@Component({
selector: 'ngif',
template: `
<h4>NgIf</h4>
<ul *ngFor="let
person of people">
<li
*ngIf="person.age <= 29">
{{ person.name }} ({{
person.age }})
</li>
</ul>`
})
class NgIfComponent {
people: any[] = [
{
"name": "Anil
Singh",
"age": 29
},
{
"name": "Alok
Singh",
"age": 33
},
{
"name": "Raju",
"age": 28
},
{
"name": "Dilip
Singh",
"age": 34
},
{
"name": "Param
Trip",
"age": 32
}
];
}
See
the below examples – Used of Angular NgSwitch –
*NgSwitchCase
import {NgModule, Component} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
@Component({
selector: 'ngswitch',
template: `<h4>NgSwitch</h4>
<ul *ngFor="let person
of people" [ngSwitch]="person.country">
<li
*ngSwitchCase="'IN'"
class="text-success">
{{ person.name }} ({{
person.country }})
</li>
<li
*ngSwitchCase="'USA'"
class="text-primary">
{{ person.name }} ({{ person.country }})
</li>
<li
*ngSwitchCase="'UK'"
class="text-danger">
{{ person.name }} ({{
person.country }})
</li>
<li
*ngSwitchCase="'NP'"
class="text-danger">
{{ person.name }} ({{
person.country }})
</li>
<li *ngSwitchDefault
class="text-warning">
{{ person.name }} ({{
person.country }})
</li>
</ul>`
})
class NgSwitchComponent {
people: any[] = [
{
"name": "Anil Singh",
"age": 29,
"country": 'IN'
},
{
"name": "Alok
Singh",
"age": 33,
"country": 'USA'
},
{
"name": "Raju",
"age": 28,
"country": 'UK'
},
{
"name": "Dilip
Singh",
"age": 34,
"country": 'NP'
},
{
"name": "Param
Trip",
"age": 32,
"country": 'USA'
}
];
}
AppComponent
-
import {NgModule, Component} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
@Component({
selector: 'directives-app',
template: `<ngswitch></ngswitch>
<ngif></ngif>`
})
class AppComponent {
}
App
Module - NgModule
@NgModule({
imports: [BrowserModule],
declarations: [
NgIfComponent,
NgSwitchComponent,
AppComponent],
bootstrap: [AppComponent]
})
class AppModule {
}
The result looks like – https://embed.plnkr.co/bjOWZQJJBvouGsJYTBwU/
I hope you are enjoying with this post! Please share with you friends!! Thank you!!!