首页 > 解决方案 > 如何在角材料下拉角5中实现全选

问题描述

我正在使用 mat-select 来显示下拉菜单,我需要在 angular 下拉菜单中选择所有功能。

下面是我的html

<mat-select formControlName="myControl" multiple (ngModelChange)="resetSelect($event, 'myControl')">
    <mat-option>Select All</mat-option>
    <mat-option [value]="1">Option 1</mat-option>
    <mat-option [value]="2">Option 2</mat-option>
    <mat-option [value]="3">Option 3</mat-option>
</mat-select>

这是我的 ts 代码

/**
 * click handler that resets a multiple select
 * @param {Array} $event current value of the field
 * @param {string} field name of the formControl in the formGroup
 */
protected resetSelect($event: string[], field: string) {
    // when resetting the value, this method gets called again, so stop recursion if we have no values
    if ($event.length === 0) {
        return;
    }
    // first option (with no value) has been clicked
    if ($event[0] === undefined) {
        // reset the formControl value
        this.myFormGroup.get(field).setValue([]);
    }
}

一些它如何无法正常工作,请帮助或让我有更好的方法来做到这一点。

标签: angulartypescriptangular-materialangular5

解决方案


使用点击事件试试这个

<mat-form-field>
  <mat-select placeholder="Toppings" [formControl]="toppings" multiple>
    <mat-option [value]="1" (click)="selectAll(ev)"   
    #ev
     >SelectAll</mat-option>
    <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
  </mat-select>
</mat-form-field>

}

打字稿:

selectAll(ev) {
    if(ev._selected) {
        this.toppings.setValue(['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato']);
        ev._selected=true;
    }
    if(ev._selected==false) {
      this.toppings.setValue([]);
    }
}

示例:https ://stackblitz.com/edit/angular-czmxfp


推荐阅读