angulartypescriptangular-materialangular-material2md-select

Dynamically uncheck multiple select options in md-select angular 4.x


I am trying to implement on click of a button in mat-select multiple, an option should get unchecked and should be removed from the checked list too.

for removing the selected option I have written my code as below :

mat-select Option:

<mat-form-field class="full-width">
          <mat-select class="multiple-location-list-search-wrapper full-width" #mulLoc required placeholder="Locations" multiple>
            <mat-option *ngFor="let l of locationsBasedOnPropertyType; let i = index" class="multiple-field-box" [hidden]="tempLocations[i]"
              [value]="l">
              {{ l.value }}
            </mat-option>
          </mat-select>
        </mat-form-field>

Delete button:

<span (click)="deleteLocation(i, mulLoc);">Delete Location</span>
          <p>
            <strong>{{mulLoc.value[i].value}}</strong>
          </p>

Delete function:

  deleteLocation(index, multipleLocation){
    multipleLocation.selected[index]._selected = false;
    multipleLocation.selected[index]._active = false;
    multipleLocation.selected.splice(index,1);
    multipleLocation.value.splice(index,1);
  }

By Implementing above, I am able to delete option from selected & value array but it's not reflecting in Material UI. Location option is not getting unchecked.

Is there any Hack or internal Method to do the same?

Thanks in advance!


Solution

  • @Will Howel, Thanks for your help man.

    But I got my solution Like below:

    I did some research in
    '..app-folder../node_modules/@angular/material/select/typings/select.d.ts'
    I found
    writeValue(value: any): void;

    The changes I made in my view :

    <mat-select class="full-width" #mulLoc required placeholder="Locations" multiple [(ngModel)]="resLoc" name="resLoc">
        <mat-option *ngFor="let l of locations; let i = index [hidden]="tempLocations[i]" [value]="l">
    {{ l.value }}
    </mat-option>
    </mat-select>
    

    Objects :

    locations = [
    {id : 'IND',value : 'india'},
    {id : 'INS',value : 'indonesia'},
    {id : 'THL',value : 'thailand'}
    ]
    resLoc = [locations[0], locations[2]]
    

    Component : this is the function which I am calling for deleting(unselecting) location

    deleteLocation(i,mulLoc) {
        this.resLoc.splice(i,1); // my ngModel
        mulLoc.writeValue(this.resLoc); // reference variable of mat-select
      }
    

    Hope it helps! happy coding!