13

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

2 Answers 2

23

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

Sign up to request clarification or add additional context in comments.

2 Comments

click and change events are different, click event will get called before the input changed plnkr.co/edit/rSxR6f88NHMBKoqDtw08?p=preview
I am getting an error for this implementation: "TS2339: Property 'checked' does not exist on type 'EventTarget'."
0

Small change which made the previous answer work for me, was casting the evt.target to HTMLInputElement:

changed(evt){
    this.isChecked  = (<HTMLInputElement>evt.target).checked    
    alert(evt.target.checked)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.