gpt4 book ai didi

angular 2 根据生活用户输入过滤 ngFor 元素?

转载 作者:太空狗 更新时间:2023-10-29 17:24:17 24 4
gpt4 key购买 nike

是否有一个插件可以在每个 keyup 事件 之后根据实时用户输入过滤使用 *ngFor 呈现的元素?

最佳答案

不需要插件!

两种可能的方式:

  • 使用过滤函数并过滤数据数组(更好的性能!)
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<input (keyup)="search($event.target.value)" />
<div *ngFor="let d of filteredData">
{{ d }}
</div>
</div>
`,
})
export class App {
name:string;
data = [
"val1",
"val2",
"val3",
"val4",
"val5",
"val6",
"test",
"huhu"
];
filteredData = this.data;

constructor() {
this.name = 'Angular2'
}

search(val: any) {
if (!val) this.filteredData = this.data;

this.filteredData = this.data.filter(d => d.indexOf(val) >= 0);
}
}

现场演示:https://plnkr.co/edit/9NtT6Z4RIg4BR1BVfh7r?p=preview

  • 或使用管道
@Pipe({ name: 'filter' })
export class FilterPipe implements PipeTransform {
public transform(values: any[], filter: string): any[] {
if (!values || !values.length) return [];
if (!filter) return values;

return values.filter(v => v.indexOf(filter) >= 0);
}
}

@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<input [(ngModel)]="filterString" />
<div *ngFor="let d of (data | filter: filterString)">
{{ d }}
</div>
</div>
`,
})
export class App {
name:string;
data = [
"val1",
"val2",
"val3",
"val4",
"val5",
"val6",
"test",
"huhu"
];

filterString = '';

constructor() {
this.name = 'Angular2'
}
}

现场演示:https://plnkr.co/edit/usgvA1hpqQ06zJxMrx4f?p=preview

关于angular 2 根据生活用户输入过滤 ngFor 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42397397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com