Angular 指令 and 管道

Master Angular 指令 and 管道 usingmethod, 提升模板 表现力

Angular 指令

指令 is Angular 模板in 特殊标记, 用于scale HTML 元素 functions or 改变其behavior.

提示

Angular 指令分 for 三class: component指令, structure指令 and property指令.

1. structure指令

structure指令用于改变 DOM structure, 它们通常以 * before 缀开头.

1.1 *ngIf 指令

*ngIf 用于条件渲染元素:

// componentclass
export class AppComponent {
  isLoggedIn = true;
}

// 模板

欢迎回来!

请先login

1.2 *ngFor 指令

*ngFor 用于遍历array并渲染list:

// componentclass
export class AppComponent {
  items = ['苹果', '香蕉', '橙子', '葡萄'];
}

// 模板
  • {{ i + 1 }}. {{ item }} ({{ isFirst ? '第一个' : '' }} {{ isLast ? '最 after 一个' : '' }} {{ isEven ? '偶数' : '奇数' }})

1.3 *ngSwitch 指令

*ngSwitch 用于 many 条件渲染:

// componentclass
export class AppComponent {
  fruit = 'apple';
}

// 模板

你选择了苹果

你选择了香蕉

你选择了橙子

未知水果

2. property指令

property指令用于改变元素 out 观 or behavior, 它们通常以 [] before 缀using.

2.1 ngClass 指令

ngClass 用于动态添加 or 移除 CSS class:

// componentclass
export class AppComponent {
  isActive = true;
  itemClass = {
    active: this.isActive,
    'text-danger': !this.isActive
  };
}

// 模板
动态classexample
in 联动态class

2.2 ngStyle 指令

ngStyle 用于动态设置 CSS 样式:

// componentclass
export class AppComponent {
  currentStyles = {
    'font-size': '20px',
    'color': 'blue',
    'font-weight': 'bold'
  };
}

// 模板
动态样式example
in 联动态样式

3. 自定义指令

可以using Angular CLI creation自定义指令:

ng generate directive highlight
// highlight.directive.ts
import { Directive, ElementRef, Input, OnInit } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective implements OnInit {
  @Input() appHighlight = 'yellow';
  
  constructor(private el: ElementRef) { }
  
  ngOnInit(): void {
    this.el.nativeElement.style.backgroundColor = this.appHighlight;
  }
}

// 模板

默认highlight

绿色highlight

红色highlight

Angular 管道

管道用于 in 模板in转换data显示, Angular providing了 many 种 in 置管道, 也可以creation自定义管道.

1. in 置管道

Angular providing了 many 种 in 置管道:

  • DatePipe: 日期format
  • UpperCasePipe: 转换 for big 写
  • LowerCasePipe: 转换 for small 写
  • CurrencyPipe: 货币format
  • DecimalPipe: numberformat
  • PercentPipe: 百分比format
  • SlicePipe: 截取array or string
  • JsonPipe: 将object转换 for JSON string
// componentclass
export class AppComponent {
  currentDate = new Date();
  text = 'Hello Angular';
  price = 123.45;
  number = 0.1234;
  items = ['苹果', '香蕉', '橙子', '葡萄'];
  user = { name: '张三', age: 25 };
}

// 模板

日期: {{ currentDate | date:'yyyy-MM-dd HH:mm:ss' }}

big 写: {{ text | uppercase }}

small 写: {{ text | lowercase }}

货币: {{ price | currency:'CNY' }}

number: {{ number | number:'1.2-4' }}

百分比: {{ number | percent:'1.2-2' }}

截取: {{ items | slice:0:2 }}

JSON: {{ user | json }}

2. 自定义管道

可以using Angular CLI creation自定义管道:

ng generate pipe reverse
// reverse.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'reverse'
})
export class ReversePipe implements PipeTransform {
  
  transform(value: string): string {
    return value.split('').reverse().join('');
  }
}

// 模板

{{ 'Hello Angular' | reverse }}

3. 管道链

可以将 many 个管道链接 in 一起using:

{{ 'Hello Angular' | reverse | uppercase }}

指令 and 管道 best practices

  1. 优先using in 置指令 and 管道, 它们经过optimization且functions完善
  2. creation自定义指令时, 保持指令 单一职责
  3. 自定义管道应保持纯functionfeatures, 避免副作用
  4. for 于 complex 逻辑, 考虑将其放 in componentclassin, 而不 is in 模板inusing many 个管道
  5. using trackBy optimization *ngFor performance

练习 1: creation自定义highlight指令

  1. creation一个名 for highlight 自定义指令
  2. 该指令应接受颜色parameter, 默认 for 黄色
  3. implementation鼠标悬停时改变highlight颜色 functions
  4. in 模板inusing该指令

练习 2: creation自定义截断管道

  1. creation一个名 for truncate 自定义管道
  2. 该管道应接受最 big long 度parameter, 默认 for 50
  3. 当文本超过最 big long 度时, 应显示省略号
  4. in 模板inusing该管道