Creating Custom Pipes in Angular
Custom Age Pipe with source code implemetation==>
Create age pipe in pipes fder by following command in command terminal
ng g p pipes/age
age.component.ts =>
age.pipe.ts =>
ageComponent.html =>
output =>29
------------------------------------------------------------------------
CUSTOM REVERSE-STRING PIPE::
reverse-str.pipe.ts ==>age.component.ts =>
DateOfBirth= new Date('01/07/1990' );
age.pipe.ts =>
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'age'
})
export class AgePipe implements PipeTransform {
transform(value: any): any {
console.log("print age pipe = " + value);
let currentDate:any = new Date().getFullYear(); // 2019
let birthYear:any = new Date(value).getFullYear();
let ageofMan:any = currentDate - birthYear;
return ageofMan;
}
}
ageComponent.html =>
<h2 class="text-center" style="color: brown;">Date Of Birth with custom 'age' pipe = {{DateOfBirth| age}}</h2>
output =>29
------------------------------------------------------------------------
CUSTOM REVERSE-STRING PIPE::
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'reverseStr'})
export class ReverseStr implements PipeTransform {
transform(value: string): string {
let newStr: string = "";
for (var i = value.length - 1; i >= 0; i--) {
newStr += value.charAt(i);
}
return newStr;
}
}
App module.ts ==>
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { ReverseStr } from './reverse-str.pipe.ts';
@NgModule({
declarations: [
AppComponent,
ReverseStr
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
AppComponent.html==>
{{ user.name | reverseStr }}
Comments
Post a Comment