How To Create Custom-Age-Filter Pipe In Angular

Pipes are use for transformations of data in angular. Angular provide some built-in pipes. also we can create custom pipe for data trsnform. We have to create custom-age-pipe.ts for age filter using below command :

  • ng g p custom-age-pipe

In custom-age-pipe.ts :

import {Pipe} from '@angular/core';

@Pipe({
  name: 'AgePipe'
})
export class AgePipe {

  transform(value:any, args?:any) {  
    let minAge = args?args:50;
    return value.filter((person:any) => {
      return person.age >= minAge;
    });
  }

}

In app.component.ts :

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  Age_range:number = 30;

  people:Array<any> = [{
    name: 'Melon',
    age: 21
  }, {
    name: 'Rio',
    age: 23
  }, {
    name: 'John',
    age: 37
  }, {
    name: 'Larra',
    age: 94
  }, {
    name: 'Den',
    age: 72
  }, {
    name: 'Larry',
    age: 42
  }];
}

In app.component.html :

<h3>Custom Age Pipe In Angular</h3>
<div>
    <p>
        0
        <input type="range" min="0" max="100" [value]="Age_range" (input)="Age_range = $event.target.value" /> 100
    </p>
    <span>{{ Age_range }}</span>
    <ul>
        <li *ngFor="let person of people | AgePipe:Age_range">
            {{ person.name }} ({{ person.age }})
        </li>
    </ul>
</div>

npm start :

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories