0
我在<li></li>
標記上使用自定義過濾管。用戶只需在<input>
中輸入一個術語,並將該列表像搜索功能一樣過濾。如何在Angular 4中使用* ngFor實現自定義過濾管道?
test.component.html
<form id="filter">
<label>Filter people by name:</label>
<input type="text" [(ngModel)]="term" />
</form>
<ul id="people-listing">
<li *ngFor="let person of people | filter:term">
<div class="single-person">
<span [ngStyle]="{background: person.belt}">{{person.belt}} belt</span>
<h3>{{person.name}}</h3>
</div>
</li>
</ul>
test.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { FilterPipe } from '../filter.pipe';
@Component({
selector: 'app-directory',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
people = [
{name: "Yoshi", belt: "black"},
{name: "Ryu", belt: "red"},
{name: "Crystal", belt: "purple"}
];
constructor() {
}
ngOnInit() {
}
}
filter.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(people: any, term: any): any {
//check if search term is undefined
if(term === undefined) return people;
//return updates people array
return people.filter(function(thisperson){
return thisperson.name.toLowerCase().includes(term.toLowerCase());
})
}
}
每當我在<input>
標籤鍵入一個名稱,帶有* ngFor的列表不會根據輸入的單詞進行過濾。
我正在使用Angular 4.1.1。
你有什麼想法如何解決上面的代碼?謝謝。
@penggy工作就像一個魅力! –