Así que estoy migrando mi sitio web a Angular y recibo este error cuando intento compilar js en ts para mi barra de navegación. Miré a mi alrededor y encontré problemas similares de otros usuarios, pero no lo estaban usando en el mismo contexto.
Aquí está el script completo y he comentado dónde está el error:
document.addEventListener("DOMContentLoaded", function(event) { const showNavbar = (toggleId, navId, bodyId, headerId) => { const toggle = document.getElementById(toggleId), nav = document.getElementById(navId), bodypd = document.getElementById(bodyId), headerpd = document.getElementById(headerId) // Validate that all variables exist if (toggle && nav && bodypd && headerpd) { toggle.addEventListener('click', () => { // show navbar nav.classList.toggle('show') // change icon toggle.classList.toggle('bx-x') // add padding to body bodypd.classList.toggle('body-pd') // add padding to header headerpd.classList.toggle('body-pd') }) } } showNavbar('header-toggle', 'nav-bar', 'body-pd', 'header') /*===== LINK ACTIVE =====*/ const linkColor = document.querySelectorAll('.nav_link') function colorLink() { if (linkColor) { linkColor.forEach(l => l.classList.remove('active')) this.classList.add('active') //error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation. } } linkColor.forEach(l => l.addEventListener('click', colorLink)) // Your code to run since DOM is loaded and ready });Cualquier ayuda es muy apreciada.
Gracias
EDITAR
Ven a descubrir que toda la sección de color de enlace se controló a través de mi secuencia de comandos de barra de navegación usando el enrutador angularLinkActive. Pude eliminar toda la sección activa del enlace de este script y no tuve ningún problema. Gracias a todos por su asistencia.
Es posible que solo necesite agregar el tipo para esto a su función de clic.
https://www.valentinog.com/blog/this/#typescript-and-this
function handleClick(this: HTMLElement) { console.log("Clicked!"); this.removeEventListener("click", handleClick); }Debe usar el argumento de event pasado a su devolución de llamada. Luego puede usar event.currentTarget para averiguar en qué elemento link_color se hizo clic realmente.
function colorLink(event: Event) { if (linkColor) { linkColor.forEach(l => l.classList.remove('active')) event.currentTarget.classList.add('active') //error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation. } }Consulte la documentación de Event.currentTarget para obtener más información.
Como bono adicional, esto funcionará ya sea que use funciones de flecha o no...
const colorLink = (event: Event) => { if (linkColor) { linkColor.forEach(l => l.classList.remove('active')) event.currentTarget.classList.add('active') //error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation. } };function colorLink() { if (linkColor) { linkColor.forEach(l => l.classList.remove('active')) this.classList.add('active') //error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation. } } Escribe esto como una función de flecha. this palabra clave está en el ámbito de la función, no en el ámbito del detector de eventos.
Entonces esa parte debería ser:
const colorLink = () => { if (linkColor) { linkColor.forEach(l => l.classList.remove('active')) this.classList.add('active') //error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation. } }