我的应用程序正在Angular 5中开发。我想先加载背景图像
<div id="mainDiv" class="sign-in" [ngStyle]="{'background-image': 'url(' + background_source + ')'}">
然后才加载页面的其余部分。
已经尝试过:
在图像完全呈现在页面上之前触发所有这些方法。
我使用Chrome的开发者选项“慢速3G网络”来模拟慢速网络
在图像渲染时,所有这些事件都已被触发。找不到一种简单的方法让它起作用。任何建议将不胜感激。提前谢谢了
我稍微调整了cat.'s answer并让它工作。
该解决方案基于this question
我们将在内存中创建一个新图像,并使用load事件来检测图像何时完成加载。
import { Directive, Input, Output, EventEmitter, ElementRef } from '@angular/core';
@Directive({
selector: '[appBackgroundImageLoaded]'
})
export class BackgroundImageLoadedDirective {
@Output() imageLoaded: EventEmitter<boolean> = new EventEmitter<boolean>(true);
constructor(private el: ElementRef) { }
ngAfterViewInit() {
const img = new Image();
const bgStyle = getComputedStyle(this.el.nativeElement).backgroundImage
const src = bgStyle.replace(/(^url\()|(\)$|[\"\'])/g, '');
img.src = src;
img.addEventListener('load', ()=> {
this.imageLoaded.emit(true);
});
}
}
和模板
<div id="mainDiv" class="sign-in" [ngStyle]="{'background-image': 'url(' + background_source + ')'}" appBackgroundImageLoaded (imageLoaded)="loaded()">