首页 > 解决方案 > 如何以角度过滤列表

问题描述

我有一个项目列表(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();
}

标签: angular

解决方案


它不是“角度过滤功能”,而是 javascript 数组过滤功能。您需要传递一个回调。

https://www.w3schools.com/jsref/jsref_filter.asp

例子:

this.listUsers = this.listUsers.filter(user => user === condition)

推荐阅读