首页 > 解决方案 > “元素”类型上不存在属性“onclick”

问题描述

我有以下角度组件

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');
      };
    }
  }

}

我正在从编译器中检索以下错误

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

尽管编译是成功的,并且所有工作都按预期进行。

我应该忽略错误吗?

标签: angulartypescript

解决方案


您需要将其转换为HTMLElement

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

推荐阅读