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 | import { Pipe, PipeTransform } from '@angular/core'; |
用@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 | // component.ts |
1 | <!-- component.html --> |
也可以直接在代码中使用pipe:
1 | import { FullNamePipe } from "../full-name.pipe"; |
Naming convention
pipe
name should be incamelCase
. -fullName
pipe
class should be inPascalCase
and end withPipe
. -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 }} |