【发布时间】:2018-04-29 16:30:09
【问题描述】:
在下面的组件视图中,
<h2>Topic listing</h2>
<form id="filter">
<label>Filter topics by name:</label>
<input type="text" [(ngModel)]="term">
</form>
<ul id="topic-listing">
<li *ngFor="let topic of topics | filter: term">
<div class="single-topic">
<!-- Topic name -->
<span [ngStyle]="{background: 'yellow'}">name - {{topic.name}}</span>
<!-- Topic type -->
<h3>{{topic.type}}</h3>
</div>
</li>
</ul>
自定义过滤器语法为:let topic of topics | filter: term
自定义过滤器在哪里:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(topics: any, term: any): any {
// check if search term is undefined
if(term === undefined) return topics;
return topics.filter(function(topic){ // javascript filter(function)
// if below is false, then topic will be removed from topics array
return topic.name.toLowerCase().includes(term.toLowerCase());
})
}
}
组件类维护topics的数据:
export class DirectoryComponent implements OnInit {
topics = [
{type:"Fiction", name:"Avatar"},
{type:"NonFiction", name:"Titanic"},
{type:"Tragedy", name:"MotherIndia"},
];
constructor() { }
ngOnInit() {
}
}
编辑:没有form标签,代码工作正常。
<label>Filter topics by name:</label>
<input type="text" [(ngModel)]="term">
为什么自定义过滤器FilterPipe 不过滤输入元素中提供的term?
【问题讨论】:
-
用管道名称发布您的完整代码
-
@Sajeetharan 缺少哪个代码?
标签: html forms angular angular-pipe