1. 程式人生 > 其它 >Angular10教程--2.4ngIf、ngSwitch、ngForOf

Angular10教程--2.4ngIf、ngSwitch、ngForOf

技術標籤:angular教程angular

ngIf、ngSwitch、ngForOf

這一節,我們將介紹angular內建指令:ngIf、ngSwitch、ngForOf。這也是日常開發中經常會遇到的常見指令。原文閱讀

ngIf

ngIf是內建的結構型指令,控制宿主元素的新增或刪除,取決於繫結的值是否為真。(跟vue的v-if是類似的,不是控制display屬性)

單獨使用ngIf

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-ng-if',
  template:
` <div *ngIf="condition">condition為真是顯示</div> `, }) export class NgIfComponent implements OnInit { condition = true; ... }

ngIf可以用於任何HTML元素。 *ngIf是個語法糖,上個例子完整的寫法如下:

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-ng-if',
  template: `
    <ng-template [ngIf]="condition">
      <div>condition為真是顯示</div>
    </ng-template>
  `
, }) export class NgIfComponent implements OnInit { condition = true; // ... }

**ng-template是一塊內嵌模板,型別是TemplateRef。(跟vue的template類似)

當然,我們平時根本就不著這麼寫,簡寫*ngIf足矣。

配合ngIfElese使用

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-ng-if',
  template: `
    <button class="btn btn-primary btn-small" (click)="condition = !condition">切換condition</button>
    <div *ngIf="condition; else elseBlock">condition為真是顯示</div>
    <ng-template #elseBlock>
      <div>condition為假是顯示</div>
    </ng-template>
  `
, }) export class NgIfComponent implements OnInit { condition = true; ... }

這裡需要注意的是:上面例子中的elseBlock並非元件中的某變數,而是TemplateRef的引用。(不帶#

使用TemplateRef

上面示例中的else後面跟的變數都是模板的引用而非元件中的變數,下面演示怎麼用元件中的變數:

// 1、引入TemplateRef、ViewChild
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';

@Component({
  selector: 'app-ng-if',
  template:  `
    <button class="btn btn-primary btn-small" (click)="condition = !condition">切換condition</button>
    <div *ngIf="condition; else elseBlocks">condition為真是顯示</div>
    <ng-template #otherTel>
      <div>condition為假是顯示</div>
    </ng-template>
  `,
})
export class NgIfComponent implements OnInit {
  condition = true;
  // 2、生命一個TemplateRef型別的變數
  elseBlocks: TemplateRef<any> = null; 
  // 3、將頁面上的引用為otherTel的template賦值給變數otherTemplate。
  // @ViewChild() 現在可以理解為:是獲取頁面元素的一種方式,後面會詳細介紹
  @ViewChild('otherTel', { static: true }) otherTemplate: TemplateRef<any> = null;

  // ...

  ngOnInit(): void {
    // 4、給聲名的變數elseBlocks賦值為otherTemplate
    this.elseBlocks = this.otherTemplate;
  }
}

問:為什麼我們需要使用變數的形式來進行條件篩選呢?

答:相較於模板的引用,變數的形式可以更加靈活。我們可以根據不同的需求,給elseBlocks賦予不同的值,而模板引用的形式只能是寫死的一段內容。

ngSwitch

ngSwitch是內建的結構型指令,控制顯示哪個模版,類似js中的switch

...
@Component({
  selector: 'app-ng-switch',
  template: `
    <p>
      <input type="radio" name="fruit" value="apple" id="apple" [(ngModel)]="fruit" />
      <label for="apple">