Angular教程

Angular ngIf指令

示例:

component.ts文件:
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-server2',
  templateUrl: './server2.component.html',
  styleUrls: ['./server2.component.css']
})
export class Server2Component implements OnInit {
 allowNewServer = false;
 serverCreationStatus = 'No server is created.';
  serverName = 'TestServer';
  serverCreated = false;
  /*constructor() {
    setTimeout(() =>{
      this.allowNewServer = true;
    }, 5000);
  }*/
  ngOnInit() {
  }
  onCreateServer() {
    this.serverCreated = true;
    this.serverCreationStatus = 'Server is created. Name of the server is' + this.serverName;
  }
  OnUpdateServerName(event: Event) {
    this.serverName = (<HTMLInputElement>event.target).value;
  }
}
component.html文件:
<p>
  Server2 is also working fine.
</p>
<label>Server Name</label>
<!--<input type="text"
       class="form-control"
       (input)="OnUpdateServerName($event)">-->
<input type="text"
       class="form-control"
[(ngModel)]="serverName">
<!--<p>{{serverName}}</p>-->
<button
  class="btn btn-primary"
  [disabled]="allowNewServer"
  (click)="onCreateServer()">Add Server</button>
<p *ngIf="serverCreated"> Server is created. Server name is {{serverName}}</p>
输出:
输出将如下所示。
使用* ngIf指令有条件地更改输出
当我们更改输入值并单击"添加服务器"按钮时,您将看到以下结果:
使用* ngIf指令有条件地更改输出
在上例中,您可以看到通过使用* ngIf指令,我们可以更改
您可以在添加服务器之前和之后检查输出的视图源。您将清楚看到差异。
添加服务器之前:
使用* ngIf指令有条件地更改输出
添加服务器后:
使用* ngIf指令有条件地更改输出
因此,您可以看到结构化指令如何更改DOM。

* ngIf指令具有其他条件

您还可以将Else条件与* ngIf指令一起使用。如果* ngIf不为真,则用于显示输出。让我们在component.html文件中进行一些更改。
component.html文件:
<p *ngIf="serverCreated; else noServer"> Server is created. Server name is {{serverName}}</p>
<ng-template #noServer>
  <p>No Server is created.</p>
</ng-template>
输出:
使用* ngIf指令有条件地更改输出
单击"添加服务器"按钮后:
使用* ngIf指令更改输出有条件的
您还可以使用否定(!)符号来检查其反向大小写。
<p *ngIf="!serverCreated; else noServer"> Server is created. Server name is {{serverName}}</p>
<ng-template #noServer>
  <p>No Server is created.</p>
</ng-template>

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4