- 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.
- Instant Apache Stanbol
- Azure IoT Development Cookbook
- Learning Neo4j 3.x(Second Edition)
- 差分進化算法及其高維多目標優化應用
- Mastering JavaScript Design Patterns(Second Edition)
- Java EE核心技術與應用
- Mastering Business Intelligence with MicroStrategy
- Learning Docker Networking
- Unity&VR游戲美術設計實戰
- Angular應用程序開發指南
- PHP與MySQL權威指南
- 小程序從0到1:微信全棧工程師一本通
- Java程序設計教程
- Visual C#(學習筆記)
- Android 5從入門到精通