如何在 Angular Mat-Select 中动态禁用特定选项

Pra*_*ale 5 angular-material2 angular angular-material-5

我有一个包含对象nameid属性的列表:

[
  {
    "name": "open",
    "id": "1"
  },
  {
    "name": "inprogress",
    "id": "2"
  },
  {
    "name": "close",
    "id": "3"
  }
]
Run Code Online (Sandbox Code Playgroud)

并使用带有 *ngFor 的 MatSelect 迭代数组并使用 select using 绑定当前状态[(ngModel)]

预期输出:

如果当前状态是inprogress禁用open选项

StackBlitz 示例

G. *_*ter 10

该示例无法正常工作,因为selected与 绑定[value]="topping.id",但逻辑使用selected.idwhich 除了在启动时不存在,因为您正在selected使用顶部对象进行初始化。

此外,该逻辑[disabled]="topping.id < selected.id"可能存在缺陷,因为它也会inprogressclose被选中时禁用- 您可能想要 - 我不确定 - 但您只是说您想openinprogress被选中时禁用。

要么使用[value]="topping"

<mat-form-field>
    <mat-select placeholder="Toppings" [(ngModel)]="selected" [formControl]="toppings">
        <mat-option *ngFor="let topping of list" [value]="topping" [disabled]="selected.id === '2' && topping.id === '1'">{{topping.name}}</mat-option>
    </mat-select>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

或者改变逻辑和初始化selected

selected: any =  '2';

<mat-form-field>
    <mat-select placeholder="Toppings" [(ngModel)]="selected" [formControl]="toppings">
        <mat-option *ngFor="let topping of list" [value]="topping.id" [disabled]="selected === '2' && topping.id === '1'">{{topping.name}}</mat-option>
    </mat-select>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

Angular v6/7 及更高版本的更新

使用[(value)]代替[(ngModel)]。对使用 ngModel 输入属性和 ngModelChange 事件与反应式表单指令的支持已在 Angular v6 中被弃用,并在 Angular v7 中被删除。


小智 1

您可以通过设置如下条件来禁用 mat-select 中的选项:

<mat-form-field>
  <mat-select placeholder="Toppings" [(ngModel)]="selected" [formControl]="toppings">
    <mat-option *ngFor="let topping of list" [value]="topping.id" [disabled]="topping.id < selected.id">{{topping.name}}</mat-option>
  </mat-select>
</mat-form-field>

<br> 
Run Code Online (Sandbox Code Playgroud)