This must be something basic which I can't figure out how to do it. I want to display in console if a check box is checked. My html and typescript code are:
<div style="display: block;margin-bottom: 10px;">
<mat-checkbox id="is3dCheckBox" (ngModel)="handleInputChange()">Split tag in bits</mat-checkbox>
</div>
And .ts file has the function handleInputChange()
handleInputChange() {
var element = <HTMLInputElement>document.getElementById("is3dCheckBox");
var isChecked = element.checked;
if (isChecked == true)
console.log("Checked");
if (isChecked == false)
console.log("Not Checked");
}
My console has no error, but it's not displaying the text when checkbox is checked. What am I doing wrong?
CodePudding user response:
You can bind to the change
event of mat-checkbox
.
Template
<mat-checkbox (change)="onChange($event.checked)"></mat-checkbox>
Component Class
onChange(checked) {
console.log(checked);
}
Also just as a side note, in Angular you should generally not feel the need to directly reference the document
object to access DOM elements. For this Angular has ElementRef.
CodePudding user response:
You just need to use a type assertion to tell TypeScript it is an HTMLInputElement: var element = document. getElementById("is3dCheckBox"); var isChecked = element.