指令概览

  1. 组件:拥有模板的指令
  2. 结构型指令:通过添加和移除 DOM 元素改变 DOM 布局的指令
  3. 属性型指令:改变元素、组件或其它指令的外观和行为的指令

    组件指令:最常用。 结构型指令:修改视图的结构。例:ngFor、ngIf 属性型指令:改变一个元素的外观或行为。例:ngStyle

结构型指令

内置结构型指令

NgIf

  1. <!--根据ngIf表达式的值,从DOM中添加或删除元素-->
  2. <app-item-detail *ngIf="isActive"></app-item-detail>

NgFor

  1. <div *ngFor="let student of students;let i=index">{{i}}{{student.name}}</div>
  1. export class DemoComponent{
  2. students: {id:number; name: string}[] = [];
  3. ngOnInit(): void{
  4. for (let i = 10; i < 20; i++) {
  5. this.students.push({ id: i, name: `学生数据${i}` });
  6. }
  7. }
  8. }

NgSwitch

  1. <div [ngSwitch]="classes">
  2. <p *ngSwitchCase="1" >一班</p>
  3. <p *ngSwitchCase="2" >一班</p>
  4. <p *ngSwitchCase="3" >三班</p>
  5. <p *ngSwitchCase="4" >四班</p>
  6. <p *ngSwitchDefault >不存在该班</p>
  7. </div>

NgSwitch 是属性型指令,ngSwitchCase 和 ngSwitchDefault 是结构型指令

属性型指令

内置属性型指令

  • NgClass:添加和删除一组 CSS 类。
  • NgStyle:添加和删除一组 HTML 样式。
  • NgModel:将数据双向绑定添加到 HTML 表单元素。

    NgClass

    ```html
    This div is special

currentClasses: { ‘saveable’: true, ‘modified’: false, ‘special’: true };

div
<a name="nNoRr"></a> ### NgStylehtml
This div is x-large or smaller.

currentStyles: { ‘font-style’: this.canSave ? ‘italic’ : ‘normal’, ‘font-weight’: !this.isUnchanged ? ‘bold’ : ‘normal’, ‘font-size’: this.isSpecial ? ‘24px’ : ‘12px’ };

This div is initially italic, normal weight, and extra large (24px).

  1. <a name="wXNyL"></a>
  2. ### [(ngModel)]
  3. ```html
  4. <input [(ngModel)]="name">
  5. export class DemoComponent implements OnInit{
  6. name = '字符串';
  7. }