2017-06-28 73 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); 
}