Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

430
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda