- Switching to Angular(Third Edition)
- Minko Gechev
- 319字
- 2021-07-02 15:23:33
Defining pipes
The syntax for defining pipes is similar to the one used for the definition of modules, directives, and components. In order to create a new pipe, we can use the ES2015 decorator, @Pipe. It allows us to add metadata to a class, declaring it as a pipe. All we need to do is provide a name for the pipe and define the data formatting logic.
During runtime, once the Angular expression interpreter finds out that a given expression includes a call of a pipe, it will retrieve it out of the pipe's collection allocated within the component and invoke it with appropriate arguments.
The following example illustrates how we can define a simple pipe called lowercase1, which transforms the given string, passed as argument to its lowercase representation:
@Pipe({ name: 'lowercase1' }) class LowerCasePipe1 implements PipeTransform { transform(value: string): string { if (!value) return value; if (typeof value !== 'string') { throw new Error('Invalid pipe value', value); } return value.toLowerCase(); } }
Using the TypeScript syntax, we implement the PipeTransform interface and define the transform method declared inside it. We will explain the TypeScript interfaces in the next chapter.
Now, let's demonstrate how we can use the lowercase1 pipe inside a component:
@Component({ selector: 'app', template: '<h1>{{"SAMPLE" | lowercase1}}</h1>' }) class App {} @NgModule({ declarations: [App, LowerCasePipe1], bootstrap: [App], imports: [BrowserModule] }) class AppModule {} platformBrowserDynamic().bootstrapModule(AppModule);
We can use the App component with the following markup:
<app></app>
The result we will see on the screen is the sample text within an h1 element. Note that we're including a reference to LowerCasePipe1 in the declarations property of the @NgModule decorator.
By keeping the data formatting logic as a separate component, Angular keeps the strong separation of concerns that can be seen throughout. We will take a look at how we can define stateful and stateless pipes for our application in Chapter 8, Explaining Pipes and Communicating with RESTful Services.
- 跟“龍哥”學C語言編程
- Python金融數據分析
- Python數據結構與算法(視頻教學版)
- C和C++游戲趣味編程
- 利用Python進行數據分析
- C語言程序設計與應用(第2版)
- HTML5+CSS3+JavaScript 從入門到項目實踐(超值版)
- Python計算機視覺和自然語言處理
- Mastering Adobe Captivate 7
- Mudbox 2013 Cookbook
- NGUI for Unity
- Java Web開發基礎與案例教程
- Node.js實戰:分布式系統中的后端服務開發
- Learning D3.js 5 Mapping(Second Edition)
- SQL Server 2014數據庫設計與開發教程(微課版)