- 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.
- Java 9 Concurrency Cookbook(Second Edition)
- 深度學習經典案例解析:基于MATLAB
- 騰訊iOS測試實踐
- Visual FoxPro 程序設計
- Mastering Python Scripting for System Administrators
- JavaScript+Vue+React全程實例
- Hands-On Swift 5 Microservices Development
- Java程序設計
- 機器學習與R語言實戰
- 運維前線:一線運維專家的運維方法、技巧與實踐
- 從Excel到Python數據分析:Pandas、xlwings、openpyxl、Matplotlib的交互與應用
- ASP.NET 4.0 Web程序設計
- Visual Basic程序設計全程指南
- 遠方:兩位持續創業者的點滴思考
- Visual Basic語言程序設計基礎(第3版)