Having different pipes is a very common case, where each pipe does a different thing. Adding each pipe to each component may become a repetitive code.
It is possible to bundle all frequently used pipes in one Module
and import that new module in any component needs the pipes.
breaklines.ts
import { Pipe } from '@angular/core';
/**
* pipe to convert the \r\n into <br />
*/
@Pipe({ name: 'br' })
export class BreakLine {
transform(value: string): string {
return value == undefined ? value :
value.replace(new RegExp('\r\n', 'g'), '<br />')
.replace(new RegExp('\n', 'g'), '<br />');
}
}
uppercase.ts
import { Pipe } from '@angular/core';
/**
* pipe to uppercase a string
*/
@Pipe({ name: 'upper' })
export class Uppercase{
transform(value: string): string {
return value == undefined ? value : value.toUpperCase( );
}
}
pipes.module.ts
import { NgModule } from '@angular/core';
import { BreakLine } from './breakLine';
import { Uppercase} from './uppercase';
@NgModule({
declarations: [
BreakLine,
Uppercase
],
imports: [
],
exports: [
BreakLine,
Uppercase
]
,
})
export class PipesModule {}
my.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-component',
template: `{{ value | upper | br}}`
})
export class MyComponent {
public value: string;
}
my.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MyComponent } from './my.component';
import { PipesModule} from './pipes.module';
@NgModule({
imports: [
BrowserModule,
PipesModule,
],
declarations: [
MyComponent,
],
})