Custom Pipes

1)app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from "@angular/platform-browser";
import { AppComponent } from './app.component';
import { StudentListComponent } from "./student-list.component";
import {ContentFilterPipe} from "./content-filter.pipe";
@NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent,StudentListComponent,ContentFilterPipe],
    bootstrap: [AppComponent]
})
export class AppModule { }

2)app.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
    moduleId: module.id,
    selector: 'project',
    template: `<div class="container-fluid">
      <h1>Student Manager</h1>
      <student-list-view></student-list-view>
    </div>`
})
export class AppComponent{}

3)content-filter.pipe.ts

import {Pipe, PipeTransform} from '@angular/core';
import {Student} from './student';
@Pipe({name: 'contentFilter', pure: false})
export class ContentFilterPipe implements PipeTransform {
  transform(value: Student[], searchFor: string) : Student[] {
    if (!searchFor) return value;
    searchFor = searchFor.toLowerCase();
    return value.filter(student => student.name.indexOf(searchFor) >= 0);
  }
}

4)student-list.component.ts

import {Component} from '@angular/core';
import {Student} from './student';
@Component({
  selector: 'student-list-view',
  templateUrl: 'student-list.template.html'
})
export class StudentListComponent {
  students = Student.students;
}

5)student-list.template.html

<div class="row">
  <div class="col-sm-12">
      Search <div class="col-sm-4 col-sm-offset-5">
      <input #searchBox class="form-control input-lg"
        placeholder="Search"
        (keyup)="0" />
  </div>
</div>
<h2>List of Students</h2>
<div class="row" *ngFor="let student of students | contentFilter:searchBox.value">
  <div class="col-sm-8">
    <h4>{{student.id}}: {{student.name | lowercase}} : {{student.pocketMoney | currency:'INR' }}:
         {{student.jeeScore }} : {{student.attemptDate | date: 'short' }}</h4>
  </div>
</div>

6)student.ts

export class Student {
    id: number;
    name: string;
    pocketMoney: number;
    jeeScore:number;
    attemptDate:Date;
    static students: Student[] = [
    { id: 1, name: 'student1',pocketMoney:1000,jeeScore:2204,attemptDate: new Date("9/27/2017 11:25")},
    { id: 2, name: 'student2',pocketMoney:5000,jeeScore:2876,attemptDate: new Date("9/27/2016 11:25")},
    { id: 3, name: 'student3',pocketMoney:2500,jeeScore:2600,attemptDate: new Date("9/27/2015 11:25")},
    { id: 4, name: 'student4',pocketMoney:7000,jeeScore:2800,attemptDate: new Date("9/27/2013 11:25")}
    ];
}

results matching ""

    No results matching ""