常用指令簡介

2018-06-07 08:46 更新

NgIf

  1. <div *ngIf="false"></div> <!-- never displayed -->
  2. <div *ngIf="a > b"></div> <!-- displayed if a is more than b -->
  3. <div *ngIf="str == 'yes'"></div> <!-- displayed if str holds the string "yes" -->
  4. <div *ngIf="myFunc()"></div> <!-- displayed if myFunc returns a true value -->

NgSwitch

有時候需要根據(jù)不同的條件,渲染不同的元素,此時我們可以使用多個 ngIf 來實現(xiàn)。

  1. <div class="container">
  2. <div *ngIf="myVar == 'A'">Var is A</div>
  3. <div *ngIf="myVar == 'B'">Var is B</div>
  4. <div *ngIf="myVar != 'A' && myVar != 'B'">Var is something else</div>
  5. </div>

如果 myVar 的可選值多了一個 'C',就得相應(yīng)增加判斷邏輯:

  1. <div class="container">
  2. <div *ngIf="myVar == 'A'">Var is A</div>
  3. <div *ngIf="myVar == 'B'">Var is B</div>
  4. <div *ngIf="myVar == 'C'">Var is C</div>
  5. <div *ngIf="myVar != 'A' && myVar != 'B' && myVar != 'C'">
  6. Var is something else
  7. </div>
  8. </div>

可以發(fā)現(xiàn) Var is something else 的判斷邏輯,會隨著 myVar 可選值的新增,變得越來越復(fù)雜。遇到這種情景,我們可以使用 ngSwitch 指令。

  1. <div class="container" [ngSwitch]="myVar">
  2. <div *ngSwitchCase="'A'">Var is A</div>
  3. <div *ngSwitchCase="'B'">Var is B</div>
  4. <div *ngSwitchCase="'C'">Var is C</div>
  5. <div *ngSwitchDefault>Var is something else</div>
  6. </div>

NgStyle

NgStyle 讓我們可以方便得通過 Angular 表達式,設(shè)置 DOM 元素的 CSS 屬性。

  • 設(shè)置元素的背景顏色

  1. <div [style.background-color="'yellow'"]>
  2. Use fixed yellow background
  3. </div>

  • 設(shè)置元素的字體大小

  1. <!-- 支持單位: px | em | %-->
  2. <div>
  3. <span [ngStyle]="{color: 'red'}" [style.font-size.px]="fontSize">
  4. red text
  5. </span>
  6. </div>

NgStyle 支持通過鍵值對的形式設(shè)置 DOM 元素的樣式:

  1. <div [ngStyle]="{color: 'white', 'background-color': 'blue'}">
  2. Uses fixed white text on blue background
  3. </div>

注意到 background-color 需要使用單引號,而 color 不需要。這其中的原因是,ng-style 要求的參數(shù)是一個 Javascript 對象,color 是一個有效的 key,而 background-color 不是一個有效的 key ,所以需要添加 ''。

NgClass

NgClass 接收一個對象字面量,對象的 key 是 CSS class 的名稱,value 的值是 truthy/falsy 的值,表示是否應(yīng)用該樣式。

  • CSS Class

  1. .bordered {
  2. border: 1px dashed black; background-color: #eee;
  3. }

  • HTML

  1. <!-- Use boolean value -->
  2. <div [ngClass]="{bordered: false}">This is never bordered</div>
  3. <div [ngClass]="{bordered: true}">This is always bordered</div>
  4. <!-- Use component instance property -->
  5. <div [ngClass]="{bordered: isBordered}">
  6. Using object literal. Border {{ isBordered ? "ON" : "OFF" }}
  7. </div>
  8. <!-- Class names contains dashes -->
  9. <div[ngClass]="{'bordered-box': false}">
  10. Class names contains dashes must use single quote
  11. </div>
  12. <!-- Use a list of class names -->
  13. <div class="base" [ngClass]="['blue', 'round']">
  14. This will always have a blue background and round corners
  15. </div>

NgFor

NgFor 指令用來根據(jù)集合(數(shù)組) ,創(chuàng)建 DOM 元素,類似于 ng1ng-repeat 指令

  1. <div class="ui list" *ngFor="let c of cities; let num = index">
  2. <div class="item">{{ num+1 }} - {{ c }}</div>
  3. </div>

使用 trackBy 提高列表的性能

  1. @Component({
  2. selector: 'my-app',
  3. template: `
  4. <ul>
  5. <li *ngFor="let item of collection;trackBy: trackByFn">{{item.id}}</li>
  6. </ul>
  7. <button (click)="getItems()">Refresh items</button>
  8. `,
  9. })
  10. export class App {
  11. constructor() {
  12. this.collection = [{id: 1}, {id: 2}, {id: 3}];
  13. }
  14. getItems() {
  15. this.collection = this.getItemsFromServer();
  16. }
  17. getItemsFromServer() {
  18. return [{id: 1}, {id: 2}, {id: 3}, {id: 4}];
  19. }
  20. trackByFn(index, item) {
  21. return index; // or item.id
  22. }
  23. }

NgNonBindable

ngNonBindable 指令用于告訴 Angular 編譯器,無需編譯頁面中某個特定的HTML代碼片段。

  1. <div class='ngNonBindableDemo'>
  2. <span class="bordered">{{ content }}</span>
  3. <span class="pre" ngNonBindable>
  4. ← This is what {{ content }} rendered
  5. </span>
  6. </div>

Angular 4.x 新特性

If...Else Template Conditions

語法

  1. <element *ngIf="[condition expression]; else [else template]"></element>

使用示例

  1. <ng-template #hidden>
  2. <p>You are not allowed to see our secret</p>
  3. </ng-template>
  4. <p *ngIf="shown; else hidden">
  5. Our secret is being happy
  6. </p>

<template> —> <ng-template>

使用示例

  1. import { Component, OnInit } from '@angular/core';
  2. import { Observable } from 'rxjs/Observable';
  3. import 'rxjs/add/observable/of';
  4. import 'rxjs/add/operator/delay';
  5. @Component({
  6. selector: 'exe-app',
  7. template: `
  8. <ng-template #fetching>
  9. <p>Fetching...</p>
  10. </ng-template>
  11. <p *ngIf="auth | async; else fetching; let user">
  12. {{user.username }}
  13. </p>
  14. `,
  15. })
  16. export class AppComponent implements OnInit {
  17. auth: Observable<{}>;
  18. ngOnInit() {
  19. this.auth = Observable
  20. .of({ username: 'semlinker', password: 'segmentfault' })
  21. .delay(new Date(Date.now() + 2000));
  22. }
  23. }

我有話說

使用 [hidden] 屬性控制元素可見性存在的問題

  1. <div [hidden]="!showGreeting">
  2. Hello, there!
  3. </div>

上面的代碼在通常情況下,都能正常工作。但當(dāng)在對應(yīng)的 DOM 元素上設(shè)置 display: flex 屬性時,盡管[hidden] 對應(yīng)的表達式為 true,但元素卻能正常顯示。對于這種特殊情況,則推薦使用 *ngIf。

直接使用 DOM API 獲取頁面上的元素存在的問題

  1. @Component({
  2. selector: 'my-comp',
  3. template: `
  4. <input type="text" />
  5. <div> Some other content </div>
  6. `
  7. })
  8. export class MyComp {
  9. constructor(el: ElementRef) {
  10. el.nativeElement.querySelector('input').focus();
  11. }
  12. }

以上的代碼直接通過 querySelector() 獲取頁面中的元素,通常不推薦使用這種方式。更好的方案是使用 @ViewChild 和模板變量,具體示例如下:

  1. @Component({
  2. selector: 'my-comp',
  3. template: `
  4. <input #myInput type="text" />
  5. <div> Some other content </div>
  6. `
  7. })
  8. export class MyComp implements AfterViewInit {
  9. @ViewChild('myInput') input: ElementRef;
  10. constructor(private renderer: Renderer) {}
  11. ngAfterViewInit() {
  12. this.renderer.invokeElementMethod(
  13. this.input.nativeElement, 'focus');
  14. }
  15. }

另外值得注意的是,@ViewChild() 屬性裝飾器,還支持設(shè)置返回對象的類型,具體使用方式如下:

  1. @ViewChild('myInput') myInput1: ElementRef;
  2. @ViewChild('myInput', {read: ViewContainerRef}) myInput2: ViewContainerRef;

若未設(shè)置 read 屬性,則默認返回的是 ElementRef 對象實例。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號