Maddy8381
Maddy8381

Reputation: 431

property classList does not exist on type 'GlobalEventHandlers' when used with angular typescript

I am implementing Collapsible in my angular application.

I have written CSS in .css file and html in .html file. And JS I have coded into .ts file as per following code.

export class HelpComponent implements OnInit {
  acc = document.getElementsByClassName("accordion") as HTMLCollectionOf < HTMLElement > ;
  constructor() {}

  ngOnInit() {
    for (let i = 0; i < this.acc.length; i++) {
      ( < HTMLButtonElement > this.acc[i]).onclick = function() {
        this.classList.toggle("active");
        var panel = < HTMLDivElement > this.nextElementSibling;
        if (panel.style.maxHeight) {
          panel.style.maxHeight = null;
        } else {
          panel.style.maxHeight = panel.scrollHeight + "px";
        }
      }
    }
  }
}

Its working fine, but I am getting error as -

"Property classList does not exist on type 'GlobalEventHandlers' and "nextSiblingElement does not exist on type 'GlobalEventHandlers'".

I have read this question - Typescript compile error: Property 'classList' does not exist on type 'Node' but I wont found the answer.

My full implementation of this code is as per previous answer suggested by @SiddAjmera on -Collapsible of CSS and JS not working in Angular app .

Need your help... Thanks in advance!

Upvotes: 2

Views: 4264

Answers (1)

Ruben Helsloot
Ruben Helsloot

Reputation: 13129

Since you already know what the element is from outside the function scope, if we assign it to a variable, you can access it inside the function.

for (let i = 0; i < this.acc.length; i++) {
  const el = < HTMLButtonElement >this.acc[i];
  el.onclick = function() {
    el.classList.toggle("active");
    var panel = < HTMLDivElement > el.nextElementSibling;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }
}

Upvotes: 1

Related Questions