admin管理员组

文章数量:1291202

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?

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?

Share Improve this question asked Aug 19, 2017 at 20:51 user8398743user8398743 0
Add a ment  | 

2 Answers 2

Reset to default 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")
 }

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
  }

本文标签: javascriptAngular check if checkbox is check from inside a functionmethodStack Overflow