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

时间:2018-07-27 05:45:01

标签: angular angular-material2 angular-material-5

我有nameid这样的列表,例如:

[
  {
    "name": "open",
    "id": "1"
  },
  {
    "name": "inprogress",
    "id": "2"
  },
  {
    "name": "close",
    "id": "3"
  }
]

然后将MatSelect与* ngFor一起使用以遍历数组,并使用[(ngModel)]与select绑定当前状态。

预期输出:

如果当前状态为inprogress,请禁用open选项

StackBlitz Example

4 个答案:

答案 0 :(得分:2)

该示例由于selected[value]="topping.id"绑定而无法正常工作,但是该逻辑使用了selected.id,因为您正在初始化{{1} }和一个顶部对象。

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

使用inprogress

[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> 的逻辑和初始化:

selected

答案 1 :(得分:0)

您可以通过设置以下条件来禁用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> 

答案 2 :(得分:0)

如果用户可以选择多个选项,我们也确实不需要ngModel,下面是我的解决方案,可以在选择角材料垫选择中的某些不同选项时禁用某些选项。

//toppings is a form control name for mat-select
this.toppings.valueChanges.subscribe((selection) => { 

this.selected = '';

//includes because in case we are using multi selection we will receive selection as array

if(selection.includes('inprogress')) // if index instead of name use index value
this.selected = 'inprogress' // selected is globally defined variable
)}

checkUserSelection(topping){

if(this.selected === 'inprogress' && topping === 'open')"{
return true;
}
return false
}

----------------- HTML代码---------------------

<mat-form-field>
<mat-select placeholder="Toppings" 
[formControl]="toppings">

<mat-option *ngFor="let topping of list" 
[value]="topping.id" 
[disabled]="checkUserSelection(topping)"
</mat-option>
</mat-select>

答案 3 :(得分:0)

我是用HTML做到的

      <mat-select [(ngModel)]="algorithm">
        <mat-option
          *ngFor="let algo of algos"
          [value]="algo.name"
          [disabled]="!algo.allow">
          {{ algo }}
        </mat-option>
      </mat-select>

和ts

 algos = ['FIFO', 'LIFO'];
    somefunctionCall(){ // Map the Array
        const fifoAllowed = false;
        isAllowed = (algo) => algo === 'FIFO' ? fifoAllowed : true;
        this.algos = this.algos.map(a => ({ name: a, allow: isAllowed(a) })
)}