'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.
Solution 1:[1]
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'));
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Chellappan வ |