prasannakumar chebrolu
prasannakumar chebrolu

Reputation: 183

TS2339: Property 'style' does not exist on type 'Element'?

Here's the code:

ngOnInit() {
const navSlide = () => {
  const burger = document.querySelector('.burger');
  const nav = document.querySelector('.nav-links');
  const navLinks = document.querySelectorAll('.nav-links li');
  burger.addEventListener('click', () => {
    nav.classList.toggle('nav-active');
  });
  navLinks.forEach((link, index) => {
  link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.3}s`;
   });
};
navSlide();

}

Error I get when compiled:

Property 'style' does not exist on type 'Element'.ts(2339)

How can I fix it?

Upvotes: 1

Views: 9201

Answers (2)

Max
Max

Reputation: 11

As T.J. said the NodeList returns NodeList of Element, another solution is type the QuerySelectorAll by yourself.

const navLinks = document.querySelectorAll<HTMLElement>('.nav-links li');

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075635

querySelectorAll returns a NodeList known to contain Elements, but not specifically HTMLElements. In your case, you know that these are HTMLElements (specifically HTMLLIElements), so you can use a type assertion saying that:

navLinks.forEach((link, index) => {
    (link as HTMLElement).style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.3}s`;
});

But see Mike S.'s comment - I don't do Angular, but it sounds like there's a more Angular-specific solution here.

Upvotes: 11

Related Questions