Reputation: 2351
i am trying to get checkbox checked value from ts(type script) file. For this, I have a Boolean variable and the purpose is to show and hide div using this variable value but I am facing a problem. Please help me to solve this and also give me the right way to do this. Here is my code...
html code
**checkbox code**abcde" class="form-check-input" id="abcde" value="1"
(change)="checked('abcde')"> abcde
show and hide code
*ngIf='shown'
ts file
checked(value) {
let get_id = document.getElementById('abcde');
if (get_id.checked == true) {
this.shown = true
}
else if (get_id.checked == false)
this.shown = false;
}
When i run ng serve then I get "Property 'checked' does not exist on type 'HTMLElement'"
Thanks in advance!
Upvotes: 22
Views: 52078
Reputation: 9
just go to your nodemodules folder
\node_modules\typescript\lib\lib.dom.d.ts
file name :lib.dom.d.ts
search for this 'Any HTML element. Some elements directly implement this interface' line no. 6374 (in my node module)
and in interface HTMLElement
add checked: boolean;
also you need to add in your global nodemodule also
press control and quick fix declare property checked: boolean;
see this image for global nodemodules
Upvotes: 0
Reputation: 181
In your HTML
<input #abcde type="checkbox" (change)="func()" />
In your component
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
@ViewChild('abcde') abcde: ElementRef;
func() {
this.abcde.nativeElement.checked
}
}
Upvotes: 6
Reputation: 2970
Use this:
const ele = document.getElementById("idOfElement") as HTMLInputElement;
ele.checked = false;
Upvotes: 59
Reputation: 2801
//Typescript File (app.component.ts)
import { Component } from 'angular/core';
@Component({
selector: 'app-root',
template: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public shown = false;
}
//Html Code (app.component.html)
<form #myForm='ngForm'>
<input type="checkbox" class="form-control"
#checkBox="ngModel"
[(ngModel)]="shown" name="checkBox">
</form>
<div *ngIf="shown">
<!---Your Code Here...--->
</div>
Here, This is one of the way to do show and hide div element on basis of checkbox selection and deselection. Two way binding is done here with shown variable.
Upvotes: 3