mat-select multiple programatically set selections

107 views Asked by At

I have a mat-select like

<mat-form-field >
    <mat-label>Ruoli</mat-label>
        <mat-select matNativeControl formControlName="_lstRoles" multiple #selectroles>
           <mat-option  *ngFor="let element of (obsTipiPersona$ | async)" [value]="element.id">
             {{element.descrizione}}
           </mat-option>
        </mat-select>
 </mat-form-field>

I need to programatically set one of the options as unflagged based on some conditions

deletedRole(who: string) {

const lstRolesControl = this.form.get('_lstRoles');
if (lstRolesControl) {
  this.obsTipiPersona$.pipe(take(1)).subscribe(options => {
    const roleToDeflag = options.find(option => option.descrizione === who);
    console.log ("option object to unflag", roleToDeflag); //THIS IS FINE

    if (roleToDeflag) {
      const selectedRolesArray = lstRolesControl.value as number[]; 
      console.log ("list of current selections", selectedRolesArray); //THIS IS FINE
      const indexToRemove = selectedRolesArray.findIndex(roleId => roleId == roleToDeflag.id); //find the one to deflag optiontoDeflag IS FINE
      console.log (indexToRemove); //THIS WORKS FINE

      if (indexToRemove !== -1) {
        selectedRolesArray.splice(indexToRemove, 1); //now it's time to remove the found option
        console.log (selectedRolesArray, "after deletion"); //THIS IS OK
        **lstRolesControl.setValue(selectedRolesArray);** //THIS IS NOT WORKING!!!
       

      }
    }
  });
}

}

everything seems fine from the console.logs. Infact I get the array of values here:

console.log (selectedRolesArray, "after deletion"); 

and it's perfect. For some reason the setvalue is not working. I noticed that I can FLAG additional items if I pass an array that contains the value of an additional option...but when I UNFLAG like this so I pass the array with the missing value this is not doing what I expect...actually it's not doing anything...the selection is still the same.

I even tried a lstRolesControl.reset()...but no way...

1

There are 1 answers

0
Nicola On

My fault......in another part of the code I had a silly function to stop deflagging

changeOptionRoles (event: MatOptionSelectionChange){

    if (!event.source.selected) {
      event.source.select();
      return;
    }}