权威教程 – 笔记05 – Angular内置指令

内置指令(6)

内置指令是已经导入过的,组件可以直接使用它们。

1 ngIf

与if语句相似
根据一个条件来决定显示或隐藏一个元素,可以使用ngIf指令。
条件是由你传给指令的表达式的结果决定的。

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

2 ngSwitch

与switch语句相似

<div class="container" [ngSwitch]="myVar">
    <div *ngSwitchCase="'A'">Var is A</div>
    <div *ngSwitchCase="'B'">Var is B</div>
    <div *ngSwitchDefault>Var is something else</div>
</div>

3 ngStyle

给特定的DOM元素设定css属性

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

4 ngClass

能动态设置和改变一个给定DOM元素的css类

  • 传入一个对象字面量。该对象希望以类名作为键,值是一个用来表明是否应该应用该类的真/假值。
  • 传入一个数组型字面量。指定哪些类名会被添加到元素上。
<div [ngClass]="{bordered: false}">
  This is never bordered
</div>

<div class="base" [ngClass]="['blue', 'round']">
 This will always have a blue background and round corners
</div>

5 ngFor

重复一个给定的DOM元素(或一组DOM元素),每次重复都会从数组中取一个不同的值。
可以嵌套
索引从0开始

<h4 class="ui horizontal divider header">
  Nested data
</h4>
<div *ngFor="let item of peopleByCity">
  <h2 class="ui header">{{ item.city }}</h2>
  <table class="ui celled table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Age</th>
      </tr>
    </thead>
    <tr *ngFor="let p of item.people">
        <td>{{ p.name }}</td>
        <td>{{ p.age }}</td>
    </tr>
  </table>
</div>

6 ngNonBindable

使用场景

  • 告诉Angular不要编译
  • 绑定页面中的某个特殊部分

有了ngNonBindable属性,Angular不会编译第二个span里的内容,而是原封不动地将其显示出来。

{
  template: `
  <div class="noNonBindableDemo">
    <span class="bordered">{{ content }}</span>
    <span class="pre" ngNonBindable>
     ← This is what {{ content }} rendered
    </span>
  </div>
  ` 
}