Property 'checked' does not exist on type 'HTMLElement' angular 4

为君一笑 提交于 2020-01-01 14:10:10

问题


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!


回答1:


//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.




回答2:


Use this:

const ele = document.getElementById("idOfElement") as HTMLInputElement;
ele.checked = false;



回答3:


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
  }
}


来源:https://stackoverflow.com/questions/48002244/property-checked-does-not-exist-on-type-htmlelement-angular-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!