angular - 如何在 Angular Material 下拉 Angular 5中实现全选

标签 angular typescript angular-material angular5

我正在使用 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>

这是我的代码

/**
 * 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([]);
    }
}

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

最佳答案

使用点击事件试试这个

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

}

typescript :

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

关于angular - 如何在 Angular Material 下拉 Angular 5中实现全选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52062927/

相关文章:

Angular 4 - 在下拉列表中找到选定的值

javascript - 引用同一个类

typescript - TypeScript 条件类型的映射与受约束的泛型不同吗?

html - 如何禁用文本区域或 mat-form-field

angular - 无法读取未定义的属性 - cdkDropListData 拖放 Angular Material

angular - 从 Angular 8 升级到 9 后出现构建错误

typescript - “Has no exported member ionicBootstrap”(ionic2 typescript )

javascript - Angular 2 没有 CompilerFactory 的提供者

javascript - typescript 新手,我对 AMD 的理解是否正确?

angular - Angular|Ionic 中“未找到 [自定义组件] 的组件工厂”