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

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.

主站蜘蛛池模板: 木兰县| 都江堰市| 宁波市| 永丰县| 同江市| 池州市| 南康市| 泸西县| 天长市| 尼玛县| 茂名市| 沛县| 甘肃省| 三门县| 澎湖县| 登封市| 凉山| 濮阳县| 尼玛县| 西乡县| 吕梁市| 奈曼旗| 砀山县| 山阴县| 芒康县| 长顺县| 曲水县| 海丰县| 桂阳县| 沅陵县| 台前县| 五常市| 四子王旗| 和林格尔县| 郎溪县| 承德市| 青铜峡市| 诸暨市| 印江| 江川县| 漾濞|