错误TS2339:类型'ElementRef <any>'不存在属性'checked'

时间:2019-06-14 14:39:08

标签: angular angular6

该代码在本地计算机上运行良好,但是在尝试使用构建版本时

ng build --prod

代码如下-

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Global } from 'src/app/global.variables';

export class FiltersComponent implements OnInit {

  @ViewChild('extraMarkRadio') extraRadioRef: ElementRef;

  constructor(
    public global: Global
  ) {
  }

  ngOnInit() {
    .....
  }


  checkExtraMarkRadio() {
    const extra_radio = this.extraRadioRef;
    extra_radio.checked = true;
  }

}

在创建内部版本时,它会引发错误-

error TS2339: Property 'checked' does not exist on type 'ElementRef<any>'

如果我将代码行更改为-

        const extra_radio = this.extraRadioRef.nativeElement;

然后构建会出现任何错误,但是在运行应用程序时会引发错误-

nativeElement is undefined.

1 个答案:

答案 0 :(得分:0)

这可能有点令人困惑,但请尝试以下操作:

第一

尝试以下

@ViewChild('extraMarkRadio' , {read: ElementRef}) extraRadioRef: ElementRef;

我们可以看到,我们正在传递第二个参数,该参数包含一个配置对象,其read属性设置为ElementRef。

如果有多个可能的可注入对象,则此read属性将确切指定我们要注入的对象。

在这种情况下,我们使用read属性指定要获取匹配模板引用的DOM元素(由ElementRef包装),而不是组件。

第二

尝试使用组件类型而不是模板引用。

相关问题