Angular2,如果未选中复选框,则禁用按钮

Kha*_*led 21 checkbox angular

我有多个复选框和一个按钮,只有在选中至少一个复选框时才需要启用该按钮

<input type="checkbox">VALUE1
<input type="checkbox">VALUE2
<input type="checkbox">VALUE3
<input type="checkbox">VALUE4
<button>Proceed</button>
Run Code Online (Sandbox Code Playgroud)

如何使用Angular2实现这一目标.

PS:发现了类似的问题,但没有使用Angular2.

Mar*_*cok 43

一种方法是ngModel在每个复选框上使用,然后disabled通过检查每个复选框模型状态的方法控制按钮的属性:

@Component({
  template: `
    <label *ngFor="let cb of checkboxes">
      <input type="checkbox" [(ngModel)]="cb.state">{{cb.label}}
    </label>
    <p><button [disabled]="buttonState()">button</button>
  `
})
class App {
  checkboxes = [{label: 'one'},{label: 'two'}];
  constructor() {}
  buttonState() {
    return !this.checkboxes.some(_ => _.state);
  }
}
Run Code Online (Sandbox Code Playgroud)

Plunker


Emi*_*ues 9

使用属性[禁用]:

<input type="checkbox" [(ng-model)]="disableButton1"> VALUE1
<input type="checkbox" [(ng-model)]="disableButton2"> VALUE1
<input type="checkbox" [(ng-model)]="disableButton3"> VALUE1
<input type="checkbox" [(ng-model)]="disableButton4"> VALUE1
<button type="button" [disabled]="disableButton || disableButton2">Submit</button>
Run Code Online (Sandbox Code Playgroud)

  • 这工作完全在一个静态代码的情况下,但正在动态创建复选框时,使用`也许是唯一的选择是使用基于选择的复选框的数量分配一个布尔变量*NG-for`说. (2认同)