首页 > 解决方案 > 禁用基于角度方法的选项

问题描述

我正在尝试根据方法禁用选项。

示例我有 4 个选项:

A
B
C
D

我的方法(示例):

if(name == A) {
disable select for A.
}

我的代码:

this.http.getDataFromServer("api/....).subscribe((resp) => {
  
  this.code = resp.data["route"];
  console.log(this.code);
});

this.code我有多个数据。这是组件中的 HTML:

            <div class="form-group">
                <label for="route_code">
                    Route Code
                </label>
                <select type="text" class="form-control" formControlName="route_code" (change)="codeSelected($event.target.value)">

               <option [value]="r.id"  *ngFor="let r of code" [disabled]="disable()">
                        {{r.code}}
                    </option>
                </select>
            </div>

在这里,我有我的 HTML 代码,r.code选项在哪里。

搜索后我找到[disable]了,我可以将它分配给一个方法disable()

Component.ts 有这个代码:

disable(){
}

我应该在 disable 方法中添加什么?例如,如果 r.code == "A",我想禁用一个选项。你能帮帮我吗?

标签: javascriptangularhtml-select

解决方案


一种选择是将要禁用的值作为参数传递:

组件.html

<div class="form-group">
    <label for="route_code">
        Route Code
    </label>
    <select type="text" class="form-control" formControlName="route_code" (change)="codeSelected($event.target.value)">
        <option [value]="r.id" *ngFor="let r of code" [disabled]="disable(r.code)">
            {{r.code}}
        </option>
    </select>
</div>

组件.ts

disable(code: string): boolean {
  return code === "A";
}

推荐阅读