Reputation: 13
I have a list of items(listUsers), and I want to filter the list. but it doesn't work. I Wonder if my method was correct or not?
this was the html file:
<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>
this was the .ts file
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();
}
Upvotes: 0
Views: 6704
Reputation: 2957
For a type of text search you can combine .filter()
and .includes()
function of vanila JavaScript to find users which are similar to the search text.
this.listUsers = this.listUsers.filter(u => u.toLowerCase().includes(searchKey.toLowerCase())
Upvotes: 0
Reputation: 78
It's not "angular filter function" but javascript array filter function. You need to pass a callback.
https://www.w3schools.com/jsref/jsref_filter.asp
Example:
this.listUsers = this.listUsers.filter(user => user === condition)
Upvotes: 1