angularcheckbox

Accessing a checkbox value on click in angular 2


I have this checkbox which i want to see if it checked through ngModel binding.
When i call console.log(activeCheckbox); i can see the ngmodel and its value property set to true in the console.
But when i call console.log(activeCheckbox.value); right after or seperately, the value is undefined?

Does anybody know what is happening here ?

<input #activeCheckbox="ngModel" (click)="checkIfActive(activeCheckbox)"
    [disabled]="pageStatus==4" [ngModel]="premiumContententPackage.active"    
    name="premiumContententPackageActive" id="premiumContententPackageActive" 
    type="checkbox" >

checkIfActive(activeCheckbox){
   console.log(activeCheckbox);
   console.log(activeCheckbox.value);
}

Solution

  • You can listen to input change event and get the state, or event assign it to any variable

    <input type="checkbox" [checked]="isChecked" (change)="changed($event)"/>
    
    
    changed(evt) {
        this.isChecked = evt.target.checked;
        alert(evt.target.checked)
      }
    

    https://plnkr.co/edit/rSxR6f88NHMBKoqDtw08?p=preview

    EDIT: The reason your code cannot see the change is because click and change events are different - click event will get called before the input changed. See https://plnkr.co/edit/rSxR6f88NHMBKoqDtw08?p=preview