0
votes

I have the following component in angular

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

}

i'm retrieving the following error from the compiler

ERROR in src/app/components/status/status.component.ts(16,16): error TS2339: Property 'onclick' does not exist on type 'Element'.

Altough the compilation is success and all works as expected.

Should i ignore the error?

2
Question aside, the way you are doing things, you are not following "Angular way". - Plochie
I agree with @Plochie. You'd be better off adopting the angular way to add handlers. The code as-is looks like trying to hang on to an older and more fragile way of writing web apps. - Andrew E

2 Answers

1
votes

You need to cast it to HTMLElement

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

As the user above mentioned, you have to cast it to HTMLElement, but inside the for loop. I don't have reputation to comment, thats why i answered again.

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

Or I would rather recommend using the "addEventListener" function, if you use "document.getElementsByClassName" anyways.

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