3

I am using Angular 4 and on my template I have a checkbox and a div.

In my .ts file I have 2 functions.

// html
<input type="checkbox" class="custom-control-input" (change)="function2($event)">

<div (click)="function1()">some text here</div>

This I have the ts file

// .ts

function1() {
   // check if the checkbox is checked.      
}

function2(event) {
    // do something here
}

From function1 how can I check if the checkbox is checked or not?

0

2 Answers 2

8

One of the ways to get the value in function1() is to use template variable.

Then you can do the followings:

1. HTML

<input #input type="checkbox" class="custom-control-input" (change)="function2($event)">

Typescript

@ViewChild('input') private checkInput;
....
function1(){
  console.log(this.checkInput.checked? "it's checked": "it's not checked")
}

2. HTML

<input #input type="checkbox" class="custom-control-input" (change)="function2($event)">
<div (click)="function1(input)">some text here</div>

Typescript

function1(element){
      console.log(element.checked? "it's checked": "it's not checked")
 }
Sign up to request clarification or add additional context in comments.

2 Comments

There's a reason why angular provides a direct way to handle forms. Actually it provides two ways (template driven forms and reactive forms) and don't forget about dynamically created forms. I suggest you actually use one of those in your answer. Your suggestion will be unrealistically or at least hard to maintain in bigger form components. How would your approach look with 30 form elements? or 100 dynamically created inputs?
@lexith, thank you! In may answer I said 'One way' in the meaning of 'one of the ways', I didn't mean to say The way. I will try to add your suggestion to my answer :)
0

Add an Id attribute to the checkbox

 <input id='check1' type="checkbox" class="custom-control-input" (change)="function2($event)">

Then check the value in function1()

function1() {
  if(document.getElementById('check1').checked) {
       // do something here
  }

Comments

Your Answer

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