javascript - Angular verificar si una casilla de verificación está marcada desde dentro de una función/método
Estoy usando Angular 4 y en mi plantilla tengo una casilla de verificación y un div.
En mi archivo .ts tengo 2 funciones.
// html
<input type="checkbox" class="custom-control-input" (change)="function2($event)">
<div (click)="function1()">some text here</div>
Este tengo el archivo ts
// .ts
function1() {
// check if the checkbox is checked.
}
function2(event) {
// do something here
}
¿Desde function1, cómo puedo comprobar si la casilla está marcada o no?
Respuesta #1
Una de las formas de obtener el valor en function1() es usar una variable de plantilla.
Entonces puedes hacer lo siguiente:
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")
}
Respuesta #2
Agrega un atributo Id al cuadro de verificación
<input id='check1' type="checkbox" class="custom-control-input" (change)="function2($event)">
Luego verifica el valor en function1()
function1() {
if(document.getElementById('check1').checked) {
// do something here
}
