oktatas:web:angular:angular_filter:pipetransform
Tartalomjegyzék
Angular PipeTransform
- Szerző: Sallai András
- Copyright © Sallai András, 2022
- 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:
- src/app/shared/pipe/empfilter.pipe.ts
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:
<table> <tr *ngFor="let employee of employees | empfilter:actPosition "> <td>{{employee.id}}</td> <td>{{employee.name}}</td> </tr> </table>
Teljes kód
app.module.ts
- app.module.ts
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 { }
empfilter.pipe.ts
- empfilter.pipe.ts
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); } }
employees.component.ts
- employees.component.ts
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 { } }
oktatas/web/angular/angular_filter/pipetransform.txt · Utolsó módosítás: 2024/08/17 11:24 szerkesztette: admin