Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material 7 Multi Select - Set selected value

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

like image 244
saran Avatar asked Dec 23 '22 22:12

saran


2 Answers

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

like image 83
ahmeticat Avatar answered Dec 28 '22 09:12

ahmeticat


see this stackblitz sample.

you can set and get value with formControl attribute.

like image 27
amir azizkhani Avatar answered Dec 28 '22 10:12

amir azizkhani