Angular 财产';onclick';不存在于类型';元素';

Angular 财产';onclick';不存在于类型';元素';,angular,typescript,Angular,Typescript,我有以下的角度分量 import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-status', templateUrl: './status.component.html', styleUrls: ['./status.component.css'] }) export class StatusComponent implements OnInit { constructor(

我有以下的角度分量

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-status',
  templateUrl: './status.component.html',
  styleUrls: ['./status.component.css']
})
export class StatusComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    const acc = document.getElementsByClassName('accordion');
    let i;
    for (i = 0; i < acc.length; i++) {
        acc[i].onclick = function() {
            this.classList.toggle('active');
            this.nextElementSibling.classList.toggle('show');
      };
    }
  }

}
从'@angular/core'导入{Component,OnInit};
@组成部分({
选择器:“应用程序状态”,
templateUrl:'./status.component.html',
样式URL:['./status.component.css']
})
导出类StatusComponent实现OnInit{
构造函数(){}
恩戈尼尼特(){
const acc=document.getElementsByClassName('accordion');
让我;
对于(i=0;i
我正在从编译器中检索以下错误

src/app/components/status/status.component.ts(16,16)中出错:错误TS2339:类型“Element”上不存在属性“onclick”

尽管编辑工作取得了成功,所有的工作都如预期的那样


我应该忽略错误吗?

您需要将其强制转换为
HTMLElement

const acc: HTMLElement = document.getElementsByClassName('accordion') as HTMLElement;

正如上面提到的用户,您必须将其强制转换为HtmleElement,但必须在for循环中。我没有名誉可以评论,这就是我再次回答的原因

  ngOnInit() {
    const acc = document.getElementsByClassName('accordion');
    let i;
    for (i = 0; i < acc.length; i++) {
        HTMLElement(acc[i]).onclick = function() {
            this.classList.toggle('active');
            this.nextElementSibling.classList.toggle('show');
      };
    }
  }
ngOnInit(){
const acc=document.getElementsByClassName('accordion');
让我;
对于(i=0;i
或者,如果您使用“document.getElementsByClassName”,我建议您使用“addEventListener”函数

ngOnInit(){
const acc=document.getElementsByClassName('accordion');
让我;
对于(i=0;i
撇开问题不谈,你做事的方式并没有遵循“棱角分明的方式”。我同意@Plochie的观点。最好采用有角度的方式添加处理程序。目前的代码看起来像是在尝试使用一种更旧、更脆弱的web应用程序编写方式。如果更改为这种方式,它将不起作用,错误将出现:类型“HtmleElement”函数
document上不存在属性“length”。getElementsByClassName()
返回一个列表。简单的方法是假设有一个元素,例如,
const acc=document.getElementsByClassName('accordion')[0]作为HTMLElement
。这是“正常”的,但您有运行时异常的风险。您可以将其分为几个阶段,首先获取列表,然后检查是否存在元素(
.length>0
),然后使用
元素[0]强制转换为HTMLElement
。我通过其他方法解决了这个问题,但使用eventListener似乎更正确。谢谢
  ngOnInit() {
    const acc = document.getElementsByClassName('accordion');
    let i;
    for (i = 0; i < acc.length; i++) {
        acc[i].addEventListener("click",function() {
            this.classList.toggle('active');
            this.nextElementSibling.classList.toggle('show');
      });
    }
  }