我使用管道过滤项目
我的输入文件位于search.html文件和List.html文件中的项目列表
模型中的更改不会触发管道转换。 请帮忙。以下是代码段。
Search.html
<input placeholder="keyword..." [(ngModel)]="search"/>
List.html
<div *ngFor="let item of items | searchPipe:'name':search ">
{{item.name}}
</div>
Search.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name : 'searchPipe',
})
export class SearchPipe implements PipeTransform {
public transform(value, key: string, term: string) {
return value.filter((item) => {
if (item.hasOwnProperty(key)) {
if (term) {
let regExp = new RegExp('\\b' + term, 'gi');
return regExp.test(item[key]);
} else {
return true;
}
} else {
return false;
}
});
}
}
答案 0 :(得分:2)
好的,根据我们的讨论和抨击,我想我有一个答案。基本上你缺少的是组件之间的沟通
搜索组件:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'my-search',
template: `
<input placeholder="keyword..." [(ngModel)]="search" (keyup)=onChange()/>
`
})
export class SearchComponent {
search: String;
@Output() onSearchChange = new EventEmitter<Object>();
onChange($event) {
this.onSearchChange.emit(this.search);
}
}
然后是一些父组件(带列表)
import { Component } from '@angular/core';
import { SearchComponent } from './search.component';
@Component({
selector: 'my-app',
template: `
<h1>Search pipe test</h1>
Search: <my-search (onSearchChange)="search = $event"></my-search>
<br/>
<br/>
<div *ngFor="let item of items | searchPipe:'name':search ">
{{item.name}}
</div>
`
})
export class AppComponent {
search: String;
items: Array<any> = [
{ id: 1, name: 'aaaaa' },
{ id: 2, name: 'bbbbb' },
{ id: 3, name: 'ccccc' },
{ id: 4, name: 'aabb' },
{ id: 5, name: 'bbcc' },
]
}