2017-06-28 29 views
1

我使用角与按钮结合。我有一个输入type"checkbox"和旁边的一个按钮。点击按钮时会调用一个方法,abc()。我必须检查复选框是否被点击按钮。复选框事件在angular2

app.component.html

<input type="checkbox" id="chckbx"> 
<button (click)="abc();" class="btn btn-success">Search </button> 

app.component.ts -

abc(){} 

回答

3

那么一个简单的解决问题的方法是使用简单的双向手动绑定

<input type="checkbox" [checked]="isChecked" (change)="isChecked = $event.target.checked" id="chckbx" style="width:30px;height:30px;" > 
<button (click)="abc();" class="btn btn-success" style="height: 30px;padding: 0px 30px">Search </button> 

    //in your component use this code 
    isChecked = false; 

    abc() { 
     if (!this.isChecked) { 
      console.log('Checkbox cannot be unchecked...'); 
     } 
    } 

它会解决这个问题。不过,我建议学习双向 数据绑定[(ngModel)]方法。但是你要进口一些 模块正确使用ngModel

2

可以传递的复选框中的click方法的参考。您需要使用#var模板标记:

<input type="checkbox" id="chckbx" #chkbox> 
<button (click)="abc(chkbox)" class="btn btn-success">Search</button> 


abc(checkbox: HTMLInputElement) { 

    console.log(checkbox.checked); 

} 
1

绑定checkbox值与ngModel。然后在abc()函数中使用它。

HTML:

<input type="checkbox" id="chckbx" style="width:30px;height:30px;" [(ngModel)]="checked" > 

<p> 
<button (click)="abc();" class="btn btn-success">Search </button> 
</p> 

app.component.ts:

checked: boolean = true; 

abc(){ 
    alert(this.checked); 
    } 

demo

1
<input type="checkbox" 
    [ngModel]="value" 
    (ngModelChange)="changeValue()" 
    id="chckbx"> 
<button (click)="abc();" class="btn btn-success">Search </button> 


changeValue() : void { 
    this.value = !this.value; 
    } 

abc() : void { 
    console.log(this.value); 
}