/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {AsyncPipe, JsonPipe, NgIf} from '@angular/common'; import {Component, OnInit, TemplateRef, ViewChild} from '@angular/core'; import {Subject} from 'rxjs'; // #docregion NgIfSimple @Component({ selector: 'ng-if-simple', imports: [NgIf], template: ` show = {{ show }}
Text to show
`, }) export class NgIfSimple { show = true; } // #enddocregion // #docregion NgIfElse @Component({ selector: 'ng-if-else', imports: [NgIf], template: ` show = {{ show }}
Text to show
Alternate text while primary text is hidden `, }) export class NgIfElse { show = true; } // #enddocregion // #docregion NgIfThenElse @Component({ selector: 'ng-if-then-else', imports: [NgIf], template: ` show = {{ show }}
this is ignored
Primary text to show Secondary text to show Alternate text while primary text is hidden `, }) export class NgIfThenElse implements OnInit { thenBlock: TemplateRef | null = null; show = true; @ViewChild('primaryBlock', {static: true}) primaryBlock: TemplateRef | null = null; @ViewChild('secondaryBlock', {static: true}) secondaryBlock: TemplateRef | null = null; switchPrimary() { this.thenBlock = this.thenBlock === this.primaryBlock ? this.secondaryBlock : this.primaryBlock; } ngOnInit() { this.thenBlock = this.primaryBlock; } } // #enddocregion // #docregion NgIfAs @Component({ selector: 'ng-if-as', imports: [NgIf, JsonPipe, AsyncPipe], template: `
Hello {{ user.last }}, {{ user.first }}!
Waiting... (user is {{ user | json }}) `, }) export class NgIfAs { userObservable = new Subject<{first: string; last: string}>(); first = ['John', 'Mike', 'Mary', 'Bob']; firstIndex = 0; last = ['Smith', 'Novotny', 'Angular']; lastIndex = 0; nextUser() { let first = this.first[this.firstIndex++]; if (this.firstIndex >= this.first.length) this.firstIndex = 0; let last = this.last[this.lastIndex++]; if (this.lastIndex >= this.last.length) this.lastIndex = 0; this.userObservable.next({first, last}); } } // #enddocregion @Component({ selector: 'example-app', imports: [NgIfSimple, NgIfElse, NgIfThenElse, NgIfAs], template: `



`, }) export class AppComponent {}