Angular Material 7 Multi Select - Set selected value

19,552

Solution 1

You can set selected values with FormControl.setValue() function

example.component.html

<mat-select [formControl]="toppings" (selectionChange)="filter($event)" multiple [(value)]="selected" >
    <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
</mat-select>

example.component.ts

  toppings = new FormControl();
  toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];

  ngOnInit(){
    this.toppings.setValue(['Mushroom', 'Onion']);
  }


  filter(data){
    console.log(data.value);
  }

Please examine example

Solution 2

see this stackblitz sample.

you can set and get value with formControl attribute.

Share:
19,552
saran
Author by

saran

Working as an IOS developer.working in swift

Updated on June 10, 2022

Comments

  • saran
    saran about 2 years

    I'm trying to set the selected value for multi select drop-down as below

    //loop to make a multiple check boxes as selected & setting based on condition

    document.getElementsByTagName('mat-pseudo-checkbox')[index].classList.add('mat-pseudo-checkbox-checked');
    document.getElementsByTagName('mat-pseudo-checkbox')[index].setAttribute("ng-reflect-state","checked");
    

    this only reflects the change cosmetically since when i try to retrieve all the selected checkbox through (selectionChange)=filter($event)

    <mat-select multiple  (selectionChange)="filter($event)" formControlName="dropdown">
       <mat-option *ngFor="let info of infos" [value]="info">
          {{info}}
        </mat-option>
     </mat-select>
    

    where the event doesn't seem to pick up the values we tried to set earlier, pls let me know how the event picks the selected values in case of mat select.

    P.S: goal is to retain multi select boxes when switching between angular tabs