如何在Angular 4中达到限制后禁用复选框?

时间:2017-06-21 03:28:42

标签: angular

以下代码限制为2个复选框,但复选框完全[禁用]并阻止(点击)事件触发,我将无法取消选中。

什么是解决方案?

这是我的HTML:

<div *ngFor="let question of questions; let i = index">
  <input type="checkbox" name="{{i}}" #name="ngModel" [disabled]="checkboxCurrent == checkboxLimit" (click)="checkboxCheck(name)" ngModel>
</div>

这是TS:

checkboxCurrent: number = 0;
checkboxLimit: number = 2;
checkboxDisabled: boolean = false;

checkboxCheck(name) {
  if (name.value != true) {
    this.checkboxCurrent ++;
    if (this.checkboxCurrent == this.checkboxLimit) {
      this.checkboxDisabled = true;
    } else {
      this.checkboxDisabled = false;
    }
  } else {
    this.checkboxCurrent --;
  }
}

1 个答案:

答案 0 :(得分:0)

像这样写一个小函数for disable

[disable]="getDisabledStatus(name)"

该功能将在下面执行:

getDisabledStatus(name):boolean  {
  if ( (name.value && checkboxCurrent == checkboxLimit) 
       || (checkboxCurrent != checkboxLimit) ) {
     return false;
  }else  {
   return true;
  }
}