管道是用來在範本中轉換資料的函式。一般來說,管道是「純粹」函式,不會造成副作用。Angular 有許多好用的內建管道,你可以匯入並在元件中使用。你也可以建立自訂管道。
NOTE: 在深入指南中進一步了解管道。
在這個練習中,你將匯入一個管道並在範本中使用它。
要在範本中使用管道,請把它包含在插值運算式中。看看這個範例:
import {UpperCasePipe} from '@angular/common';
@Component({
...
template: `{{ loudMessage | uppercase }}`,
imports: [UpperCasePipe],
})
export class App {
loudMessage = 'we think you are doing great!'
}
現在,換你來試試看:
-
匯入
LowerCase管道首先,更新
app.ts,從@angular/common加上LowerCasePipe的檔案層級匯入。import {LowerCasePipe} from '@angular/common'; -
把管道加到範本的 imports 中
接著,更新
@Component()裝飾器的imports,加入對LowerCasePipe的參照@Component({ ... imports: [LowerCasePipe] }) -
把管道加到範本中
最後,在
app.ts中更新範本,加入lowercase管道:template: `{{ username | lowercase }}`
管道也可以接受參數,用來組態它們的輸出。在下一個練習中了解更多。
P.S. 你做得很好 ⭐️