0%

angular-pipe

What is a pipe

Angular中的pipe就是一个简单的函数,该函数接收一个输入值,然后返回一个转换后的值。pipe只需在一处定义,然后任意模板都可使用。

Generate pipe

1
ng generate pipe full-name

This will create a new file full-name.pipe.ts in the src/app folder.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { Pipe, PipeTransform } from '@angular/core';

interface Person {
firstName: string;
lastName: string;
}

@Pipe({
name: 'fullName',
standalone: true
})
export class FullNamePipe implements PipeTransform {
transform(value: Person, ...args: unknown[]): unknown {
return value.lastName + ', ' + value.firstName;
}
}

用@Pipe装饰器来定义pipe,name属性是pipe的名字,standalone属性是可选的,如果设置为true,则表示该pipe是一个独立的pipe,不依赖于任何Module。pure参数是可选的,默认为true。pure pipe只有当输入变化时才重新计算。

每个Pipe都实现了PipeTransform接口,该接口只有一个方法transform,该方法接收一个输入值和一些可选参数,然后返回一个转换后的值。在这里,我们根据输入的Person变量,返回对应的全名。

How to use pipe

在component中引入pipe,然后在模板中使用。上面的FullNamePipe可以这样使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// component.ts
import {FullNamePipe} from "../full-name.pipe";

@Component({
// ...
imports: [
FullNamePipe,
],
// ...
})

person = {
firstName: 'Philip',
lastName: 'Zhang',
}
1
2
<!-- component.html -->
{{ person | fullName }}

也可以直接在代码中使用pipe:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { FullNamePipe } from "../full-name.pipe";

@Component({
// ...
providers: [FullNamePipe],
})
export class YourComponent {
person = {
firstName: 'Philip',
lastName: 'Zhang',
};

constructor(private fullNamePipe: FullNamePipe) {
const fullName = this.fullNamePipe.transform(this.person);
console.log(fullName); // logs "Zhang, Philip"
}
}

Naming convention

  1. pipe name should be in camelCase. - fullName
  2. pipe class should be in PascalCase and end with Pipe. - FullNamePipe

Pass parameter to pipe

pipe可以接收多个参数,参数之间使用:分隔。

1
{{ value | pipe:param1:param2... }}

Pipe chaining

多个pipe可以使用|符号连接在一起,前一个pipe的输出会作为后一个pipe的输入。

1
{{ value | pipe1 | pipe2 | pipe3 }}

Pipe precedence

pipe的执行顺序是从左到右,并且pipe的优先级高于 :?操作符.

Bad

1
{{ value > 0 ? expression1 : expression2 | pipe }}

is equal to

1
{{ value > 0 ? expression1 : (expression2 | pipe) }}

Good

1
{{ (value > 0 ? expression1 : expression2) | pipe }}

References

https://angular.io/guide/pipes-custom-data-trans