【问题标题】:Disable option based on method in angular禁用基于角度方法的选项
【发布时间】:2021-10-26 10:55:14
【问题描述】:

我正在尝试禁用基于方法的选项。

例如我有 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",我想禁用一个选项。你能帮帮我吗?

【问题讨论】:

    标签: javascript angular html-select


    【解决方案1】:

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

    component.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";
    }
    

    【讨论】:

      【解决方案2】:

      你可以在你的方法中传递当前的r

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

      然后在禁用方法中,您可以像这样接收您传递的值。

      disable(r){
       return r.code === "A";
      }
      

      此表达式将返回 truefalse

      这个解决方案应该可以工作。

      【讨论】:

        猜你喜欢
        • 2019-09-20
        • 2020-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-12
        • 2023-03-27
        • 2015-09-12
        相关资源
        最近更新 更多