属性'已检查'在类型'HTMLElement'angle 4上不存在

rai*_*han 3 checkbox angular

我试图从ts(类型脚本)文件中获取复选框选中的值.为此,我有一个布尔变量,目的是使用此变量值显示和隐藏div,但我遇到了问题.请帮我解决这个问题,并给我正确的方法来解决这个问题.这是我的代码......

HTML代码

**checkbox code**abcde" class="form-check-input" id="abcde" value="1"
(change)="checked('abcde')"> abcde
Run Code Online (Sandbox Code Playgroud)

显示和隐藏代码

*ngIf='shown'
Run Code Online (Sandbox Code Playgroud)

ts文件

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;
}
Run Code Online (Sandbox Code Playgroud)

当我运行服务然后我得到"属性'检查'不存在类型'HTMLElement'"

提前致谢!

Mic*_*ips 6

用这个:

const ele = document.getElementById("idOfElement") as HTMLInputElement;
ele.checked = false;
Run Code Online (Sandbox Code Playgroud)


小智 5

在您的HTML中

<input #abcde  type="checkbox" (change)="func()" />
Run Code Online (Sandbox Code Playgroud)

在您的组件中

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
  }
}
Run Code Online (Sandbox Code Playgroud)


khu*_*ush 3

//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>
Run Code Online (Sandbox Code Playgroud)

在这里,这是基于复选框选择和取消选择来显示和隐藏 div 元素的方法之一。此处使用显示的变量完成两种方式的绑定。