Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

429
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!