官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 黄浦区| 安阳县| 静海县| 循化| 漳州市| 龙游县| 和林格尔县| 陈巴尔虎旗| 红桥区| 普格县| 淳安县| 柯坪县| 庆元县| 绥阳县| 绿春县| 句容市| 临潭县| 巩义市| 本溪| 七台河市| 天峻县| 东宁县| 长沙市| 探索| 华安县| 德州市| 吐鲁番市| 合肥市| 综艺| 沈阳市| 黄浦区| 九龙坡区| 筠连县| 湾仔区| 仪征市| 新昌县| 怀宁县| 鄂尔多斯市| 开原市| 张家港市| 西乌|