Angular Material 7 Multi Select - Set selected value

 ̄綄美尐妖づ 提交于 2019-12-08 07:33:15

问题


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


回答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




回答2:


see this stackblitz sample.

you can set and get value with formControl attribute.




回答3:


Here is working good link example



来源:https://stackoverflow.com/questions/57107587/angular-material-7-multi-select-set-selected-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!