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?
ViewChild
to get references to your elements, as it is the way angular intends it for you to get references to dom elements. navSlide
and put it in the playground: typescriptlang.org/play/… querySelectorAll
returns a NodeList
known to contain Element
s, but not specifically HTMLElement
s. In your case, you know that these are HTMLElements
(specifically HTMLLIElement
s), 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.
ngAfterViewInit
instead of ngOnInit
, as the view is only initialized then. 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');