[[oktatas:web:angular:angular_filter|< Angular filter]] ====== Angular PipeTransform ====== * **Szerző:** Sallai András * Copyright (c) Sallai András, 2022 * Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC Attribution-Share Alike 4.0 International]] * Web: https://szit.hu ===== Kezdés ===== Projekt létrehozása: ng new app01 Komponens létrehozása: ng generate component employees Röviden: ng g c employees ===== Pipe generálása ===== ng g p shared/pipe/empfilter Rövidítve: ng g p shared/pipe/empfilter Ezt kapjuk: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'empfilter' }) export class EmpfilterPipe implements PipeTransform { transform(value: unknown, ...args: unknown[]): unknown { return null; } } Az app.module.ts fájlban vegyük fel (Az //ng g p// parancs automatikusan beteszi): declarations: [ EmpfilterPipe ], Írjuk meg a szűrőt: transform(values: any[], filter: Number): any { if (!values || !filter) { return values; } return values.filter(value => value.positionId == filter); } A szűrő használata:
{{employee.id}} {{employee.name}}
===== Teljes kód ===== import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { EmployeesComponent } from './employees/employees.component'; import { EmpfilterPipe } from './shared/pipe/empfilter.pipe'; @NgModule({ declarations: [ AppComponent, EmployeesComponent, EmpfilterPipe ], imports: [ BrowserModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'empfilter' }) export class EmpfilterPipe implements PipeTransform { transform(values: any[], filter: Number): any { if (!values || !filter) { return values; } return values.filter(value => value.positionId == filter); } } import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-employees', templateUrl: './employees.component.html', styleUrls: ['./employees.component.css'] }) export class EmployeesComponent implements OnInit { actPosition !: number; employees = [ {"id": 1, "name": "Peres Béla", "positionId": 1}, {"id": 2, "name": "Energia Árpád", "positionId": 1}, {"id": 3, "name": "Gyenge Valér", "positionId": 2}, {"id": 4, "name": "Pásztó László", "positionId": 2}, {"id": 5, "name": "Trombita Béla", "positionId": 3}, {"id": 6, "name": "Rendes Lajos", "positionId": 3}, ]; constructor() { } ngOnInit(): void { } }

Dolgozók

{{employee.id}} {{employee.name}}