Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

442
Vistas
In Angular, how can I run a small script on each component that gets loaded? (diagnostic purposes)

I want to run certain diagnostic lines of Javascript as I develop that will console log the alt attribute on all <img> tags in the HTML, for instance. This is purely for testing and will not go to production of course. On a single component I would normally run this within the ngAfterContentInit() and/or ngOnChanges() lifecycle hooks, so it would run this script whenever the images in the HTML have been loaded and rendered.

The JS would just be something simple like getElementsByTagName('img')[0].getAttribute('alt'), but how can I run this each time a component is displayed, so I can check these kinds of things without adding an import to each individual component? Is there something I can do in the AppModule for instance that controls the components that are loaded? I would like to run these kinds of scripts on dynamically/lazily loaded components too, if that is possible.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use a custom directive for this purpose, Define global img selector in custom directive. Then use ElementRef class to access image alt attributes value.

import { Directive, ElementRef, isDevMode, OnInit } from '@angular/core';
@Directive({
  selector: 'img',
})
export class ImgDirective implements OnInit {
  constructor(private element: ElementRef) {}

  ngOnInit() {
    if (isDevMode) {
      console.log(this.element.nativeElement.getAttribute('alt'));
    }
  }
}

Working Example

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda