user8226204
user8226204

Reputation:

checkbox event binding with button in angular2

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(){}

Upvotes: 3

Views: 8917

Answers (4)

Raheel Anwar
Raheel Anwar

Reputation: 267

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.

Upvotes: 7

Yoav Schniederman
Yoav Schniederman

Reputation: 5391

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

Upvotes: 1

Nehal
Nehal

Reputation: 13307

Bind the checkbox value with ngModel. Then use it in the abc() function.

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

Upvotes: 0

Poul Kruijt
Poul Kruijt

Reputation: 71911

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);  

}

Upvotes: 4

Related Questions