Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checkbox event binding with button in angular2

Tags:

angular

I'm using angular. I have an input type"checkbox" and a button next to it. When clicking the button a method is called, abc(). I have to check whether checkbox is checked or not on the click of button.

app.component.html

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

app.component.ts-

abc(){}

2 Answers

Well a simple solution to your problem is to use simple two way binding manually

<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...');
        }
    }

It will solve the problem. However I do recommend to learn two way data-binding [(ngModel)] approach. But you have to import some modules properly to use ngModel.

like image 153
Raheel Anwar Avatar answered Jul 15 '26 11:07

Raheel Anwar


You can pass the reference of the checkbox in the click method. You need to use the #var template notation:

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


abc(checkbox: HTMLInputElement) {

    console.log(checkbox.checked);  

}
like image 29
Poul Kruijt Avatar answered Jul 15 '26 10:07

Poul Kruijt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!