admin管理员组

文章数量:1277875

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 piled:

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

How can I fix it?

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 piled:

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

How can I fix it?

Share Improve this question asked Jun 2, 2020 at 8:07 prasannakumar chebroluprasannakumar chebrolu 1831 gold badge3 silver badges17 bronze badges 5
  • Can you provide a reproducible example? Also you should be using ViewChild to get references to your elements, as it is the way angular intends it for you to get references to dom elements. – user13258211 Commented Jun 2, 2020 at 8:13
  • @MikeS. - The above is reproducible if you take the body of navSlide and put it in the playground: typescriptlang/play/… – T.J. Crowder Commented Jun 2, 2020 at 8:14
  • @MikeS. - The Angular part of your ment could be the basis for a good answer, though, IMHO. – T.J. Crowder Commented Jun 2, 2020 at 8:15
  • 1 stackoverflow./questions/58773652/… – Darren Street Commented Jun 2, 2020 at 9:22
  • Does this answer your question? TS2339: Property 'style' does not exist on type 'Element' – sumitkm Commented Jun 2, 2020 at 10:33
Add a ment  | 

2 Answers 2

Reset to default 11

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 ment - I don't do Angular, but it sounds like there's a more Angular-specific solution here.

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

本文标签: javascriptTS2339 Property 39style39 does not exist on type 39Element39Stack Overflow