[英]How to implement Custom Filter Pipe with *ngFor in Angular 4?
I am using a custom filter pipe on a <li></li>
tag.我在
<li></li>
标签上使用自定义过滤器管道。 The user will just type a term in the <input>
and the list is filtered like a search function.用户只需在
<input>
一个术语,列表就会像搜索功能一样被过滤。
test.component.html测试组件.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 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 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());
})
}
}
Whenever I type a name in the <input>
tag, the list with *ngFor is NOT filtered according to the typed word.每当我在
<input>
标签中<input>
名称时,带有 *ngFor 的列表不会根据输入的单词进行过滤。
I am using Angular 4.1.1.我正在使用 Angular 4.1.1。
Do you have any idea how to fix the code above?你知道如何修复上面的代码吗? Thanks.
谢谢。
bind your input with name
property.将您的输入与
name
属性绑定。
<form id="filter">
<label>Filter people by name:</label>
<input type="text" name="people" [(ngModel)]="term" />
</form>
Also make sure you have add FilterPipe
to declarations
of NgModule
.另外,请确保您有加
FilterPipe
以declarations
的NgModule
。
感谢您的时间,但有一些错误,您还必须在@component 文件 test.component.ts 中指定过滤器的定义位置,您尝试导入它但您没有使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.