Angular Material 7 Multi Select - 设置选定值

sar*_*ran 3 angular-ui angular-material angular-material2 angular

我正在尝试为多选下拉菜单设置选定的值,如下所示

//循环以根据条件选择和设置多个复选框

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

这仅从外观上反映了更改,因为当我尝试通过 (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>
Run Code Online (Sandbox Code Playgroud)

如果事件似乎没有选择我们之前尝试设置的值,请​​让我知道事件如何在 mat select 的情况下选择选定的值。

PS:目标是在角度选项卡之间切换时保留多选框

ahm*_*cat 8

您可以使用FormControl.setValue()功能设置选定的值

示例.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>
Run Code Online (Sandbox Code Playgroud)

示例.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);
  }
Run Code Online (Sandbox Code Playgroud)

请检查示例