Issue
While trying to filter the options visible inside a mat-selection-list
by modifying the array on which the ngFor
iterated on to generate the available mat-list-option
I am losing the existing state of which options were checked since an ngModelChange
event is fired even though, the user didn't really click on anything
<mat-selection-list
name="userSelection"
[ngModel]="selectedUsers"
(ngModelChange)="onSelectedUsersChange($event)">
<mat-list-option *ngFor="let user of users"
[value]="user"
checkboxPosition="before"
[title]="user.name">
{{ user.name }}
</mat-list-option>
</mat-selection-list>
And the typescript code:
applyUserSearchFilter(username: string) {
if (!isNullOrWhitespace(username)) {
this.users = this.usersOriginal.filter(
u => u.name.toLowerCase().indexOf(username.toLowerCase()) > -1
);
} else {
this.users = this.usersOriginal;
}
}
onSelectedUsersChange(e: any) {
this.selectedUsers = e;
}
When running this method, if I have two options A
and B
, both checked and then run this while filtering for C
, both options disappear, which is what I want.
But then when I clear the filter, both options are visible again but not checked.
The reason for this I suspect is when both options disappear because of the filter, onSelectedUsersChange
is triggered, with an empty array.
Is there any way I can selectively not trigger that event, or know whether onSelectedUsersChange
was triggered due to user interaction or script cascading events ?
Solution
The solution to this was to use selectionChange
instead of ngModelChange
while still binding with ngModel
.
selectionChange
passes an object with which you can either push into or splice selectedUsers
based on whether the option is selected on not.
Lastly, at the end of applyUserSearchFilter
I made sure the user selection is reapplied by adding this.selectedUsers = clone(this.selectedUsers);
. clone
is a method we have to clone objects.
Answered By - Francis Ducharme
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.