I'm implementing a lazy image loader in my Angular (5) app, and am curious how I can avoid having to call setTimeout()
in my ngAfterViewInit()
, if possible.
The relevant portions of the code are:
# component
ngOnInit(): void {
this.workService.getCategories().then(workCategories => {
this.workCategories = workCategories;
});
}
ngAfterViewInit(): void {
setTimeout(() => {
const images = Array.from(document.querySelectorAll('.lazy-image'));
}, 100);
}
# component template
<div *ngFor="let workCategory of workCategories">
<h3>{{ workCategory.fields.name }}</h3>
<div *ngFor="let workSample of workCategory.fields.workSamples">
<img width="294" height="294" class="lazy-image" src="..." data-src="..." />
</div>
</div>
If I remove setTimeout()
the images array is always empty. AfterViewInit should run after all of the child components have been created. I've also tried AfterContentInit, which behaves the same and AfterContentChecked, which crashed Chrome.
Is it possible to avoid setTimeout in this case?