我有一个项目列表(listUsers),我想过滤该列表。但这不起作用。我想知道我的方法是否正确?
这是html文件:
<div class="search-div">
<mat-form-field class="search-form-field" floatLabel="never" style="display: flex;`justify-content: center;">
<input matInput [(ngModel)]="searchKey" placeholder="Search" autocomplete="off" (keyup)="applyFilter()">
<button mat-button matSuffix mat-icon-button aria-label="Clear" *ngIf="searchKey" (click)="onSearchClear()">
<mat-icon>close</mat-icon>
</button>
</mat-form-field>
<mat-selection-list >
<mat-list-option *ngFor="let d of listUsers" >{{d.username}}</mat-list-option>
</mat-selection-list>
</div>
这是.ts文件
listUsers: any;
ngOnInit() {
this.userService.getAll()
.subscribe(data => {
this.listUsers = data;
console.log(this.listUsers);
});
}
onSearchClear() {
this.searchKey = '';
}
applyFilter(value: string) {
this.listUsers.filter = this.searchKey.trim().toLowerCase();
}
答案 0 :(得分:0)
这不是“角度过滤器功能”,而是javascript数组过滤器功能。您需要传递回调。
https://www.w3schools.com/jsref/jsref_filter.asp
示例:
this.listUsers = this.listUsers.filter(user => user === condition)
答案 1 :(得分:0)
对于一种文本搜索,您可以结合使用Vanila JavaScript的.filter()
和.includes()
函数来查找与搜索文本相似的用户。
this.listUsers = this.listUsers.filter(u => u.toLowerCase().includes(searchKey.toLowerCase())