使用 mat-optgroup 将全选按钮添加到 mat-select

Ard*_*nne 2 angular angular5

我想将“全选”和“取消全选”按钮添加到带有组划分的垫子选择中。

我的代码在这里可用:https : //stackblitz.com/edit/angular5-selectall-with-groups?file=app/select-reset-example.html

此代码基于此用于简单 mat-select 的工作演示:https : //stackblitz.com/edit/angular-material-select-multi-c6vtux?file=app%2Fapp.component.ts

在我的代码中,我需要遍历 4 个数组,因此我开始测试第一个数组的“selectAll()”函数。但是,即使 [ngModel] 显示该函数采用数组内的所有值,也只会选中第一个复选框。我还需要使这个函数适用于其他三个数组。

我希望有人能帮我解决这个问题。如果有更好的方法来完成我想要实现的目标,我也可以更改代码。

har*_*mar 6

* 我也请更新您的代码* https://stackblitz.com/edit/angular5-selectall-with-groups?file=app%2Fselect-reset-example.ts

HTML代码是这样的

 <form [formGroup]="roleForm " (ngSubmit)="onSubmit(roleForm .value)">

     <!-- Multi Select Mat Start -->
              <mat-form-field class="example-full-width">

                <mat-select placeholder="Select Privileges"  #selectedValues  class="filter-select" formControlName="privilegeMultiselect" 
                  multiple required >
                  <mat-option disabled="disabled" class="filter-option">
                    <button mat-raised-button class="mat-primary fill text-sm" (click)="selectAll(dropdownList)">
                      Select All 
                    </button>
                    <button  mat-raised-button class="mat-primary fill text-sm eta-margin-all" (click)="deselectAll()">
                      Deselect All
                    </button>
                  </mat-option>
                  <mat-option *ngFor="let privilege of dropdownList" [value]="privilege.id">{{privilege.itemName}}</mat-option>
                </mat-select>

              </mat-form-field>
              <!-- Multi select mat end -->

    </form>
Run Code Online (Sandbox Code Playgroud)

在ngoninit方法中创建表单构建器

this.roleForm = this._formBuilder.group({
      privilegeMultiselect: []

    })
Run Code Online (Sandbox Code Playgroud)

这些是您选择价值的方法

selectAll(list) {

    this.roleForm.get('privilegeMultiselect').patchValue(list)
  }
  deselectAll() {
    this.roleForm.get('privilegeMultiselect').patchValue([])
  }
Run Code Online (Sandbox Code Playgroud)