【问题标题】:how to disable checkbox based on particular value in loop using angular 6?如何使用角度6根据循环中的特定值禁用复选框?
【发布时间】:2020-01-08 04:43:42
【问题描述】:

如果 value = 2,我想禁用复选框。这是我迄今为止尝试过的。

discheckcondition = [1,2,3];

for (let x = 0; x < this.discheckcondition.length; x++) {
    // console.log(this.discheckcondition[x]);
    if (this.discheckcondition[x] = '2') {
        console.log(this.discheckcondition[x]);
        this.disablecheckfornext = '1';
    };
}
<ng-container *ngFor="let value of values;">
 <label>
  <input id="checkbox_group1" type="checkbox" pattern="[0-9]{10}" [disabled]=" disablecheckfornext == '1'"  value="value.id" (change)="onCheckboxChange($event)"/>
 </label>
</ng-container>

有人可以帮助我吗?这里的问题是所有文本框都被禁用了。

【问题讨论】:

  • 您在这里使用了赋值运算符:if (this.discheckcondition[x] = '2')。应该是 == 或 ===
  • 我试过用它。它在这里不起作用。
  • 为什么要在 ngFor 循环之外更新 disablecheckfornext。因为 ng-container 是由值集合驱动的。我建议值集合应该具有类似 value.disabled 的属性,以便可以用作 [disabled] = " value.disabled == '1' "。

标签: javascript angular angular6


【解决方案1】:

如果 Checkbox 在 ngFor 循环中,此代码将起作用

discheckcondition = [1,2,3];

for (let x = 0; x < this.discheckcondition.length; x++) {   
        this.disablecheckfornext[x] = false;
    if (this.discheckcondition[x] = '2') {       
        this.disablecheckfornext[x] = true;
    };
}
&lt;input id="checkbox_group1" type="checkbox" pattern="[0-9]{10}" [disabled]=" disablecheckfornext[#i]"  value="" (change)="onCheckboxChange($event)"/&gt;

【讨论】:

  • 上述解决方案没有运气
【解决方案2】:

您可以使用索引来做到这一点。

<ng-container *ngFor="let value of values;let i = index;">
 <label>
  <input id="checkbox_group1" type="checkbox" pattern="[0-9]{10}" [disabled]=" values[i].id === 2"  value="value.id" (change)="onCheckboxChange($event)"/>
 </label>
</ng-container>

【讨论】:

    【解决方案3】:

    使用属性'[attr.disabled]'实现条件式。

    <input id="checkbox_group1" type="checkbox" [attr.disabled] = "disablecheckfornext == '1' ? 'disabled' : null" (change)="onCheckboxChange($event)"/>
    

    【讨论】:

      猜你喜欢
      • 2019-01-17
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 2021-02-22
      • 2019-03-13
      • 1970-01-01
      相关资源
      最近更新 更多