Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Angular 4 If Else and Then Conditions [5 Best Examples]

Angular 4 if else then conditions

Syntax:-
*ngIf="[condition expression]; else [else template]"> 

Syntax:-
*ngIf="users | async; else loadingGrid; let user">
{{user.Id}}
{{user.name}}
{{user.Age}}


-template #loadingGrid>loading.../ng-template>

Syntax :- We can also use 'then else'
*ngIf="isValid;then then_content else other_content">If IsValid then display other


-template #then_content>content here.../ng-template>
-template #other_content>other content here.../ng-template>

Example 1 as,
*ngIf="isValid;else other_content">
Display valid content here ...


-template #other_content>
Other content here...
/ng-template>

Example 2 as,
*ngIf="title; then logout else login">


-template #login>Please login to continue./ng-template>
-template #logout>Hi Anil!Logout./ng-template>

Example 3 as,
//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
selector: 'else-cmp',
template: `button (click)="isValid = !isValid">update/button>
div *ngIf="isValid; else other_content">
content here ...
/div>
ng-template #other_content>other content here.../ng-template>`,
})
export class ElseComponent {
isValid:boolean = true;
constructor() {
}
}
@Component({
selector: 'else-then-cmp',
template: `
button (click)="isValid = !isValid">update/button>
div *ngIf="isValid;then content else other_content">/div>
ng-template #content>content here.../ng-template>
ng-template #other_content>other content here.../ng-template>
`,
})
export class ElseThenComponent {
isValid:boolean = true;
constructor() {
}
}

@Component({
selector: 'my-app',
template: `
h4>Using else :/h4>
else-cmp>/else-cmp>
h4>Using else then:/h4>
else-then-cmp>/else-then-cmp>
`,
})
export class App {
isValid:boolean = true;
constructor() {
}
}

@NgModule({
imports: [ BrowserModule ],
declarations: [ App , ElseComponent, ElseThenComponent],
bootstrap: [ App ]
})
export class AppModule {}

Stayed Informed - Best Angular 2 Interview Questions and Answers

I hope you are enjoying with this post! Please share with you friends. Thank you!!


This post first appeared on Programming, please read the originial post: here

Share the post

Angular 4 If Else and Then Conditions [5 Best Examples]

×

Subscribe to Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×