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

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.

主站蜘蛛池模板: 钟山县| 广南县| 盐池县| 开封市| 尼玛县| 天长市| 衡山县| 新宁县| 五莲县| 明光市| 中卫市| 连南| 安多县| 红安县| 沛县| 涿鹿县| 南皮县| 比如县| 灌阳县| 利辛县| 安图县| 武乡县| 革吉县| 商河县| 邳州市| 盖州市| 乐至县| 神农架林区| 清新县| 宁武县| 金川县| 锦州市| 衡阳县| 河曲县| 来凤县| 阆中市| 延吉市| 洛扎县| 屏南县| 措美县| 黄梅县|