sah*_*kho 1 typescript viewchild angular angular-lifecycle-hooks
我实际上正在研究 Angular,我想知道是否有办法知道图像是否已正确加载到 dom 中。我尝试使用this.image.nativeElement.width,但宽度是在图像加载之前发送的。
超文本标记语言
<img #image [src]="imagePath">
Run Code Online (Sandbox Code Playgroud)
TS
@ViewChild('image', {static: true})
image: ElementRef<HTMLImageElement>;
Run Code Online (Sandbox Code Playgroud)
您可以通过两种方式完成此操作:
使用 AfterViewInit 并访问元素
@ViewChild('image')
public img: ElementRef;
ngAfterViewInit() {
const image: HTMLImageElement = this.img.nativeElement;
image.onload = () => {
console.log('image loaded');
};
}
Run Code Online (Sandbox Code Playgroud)
使用(加载)事件
<img #image [src]="imagePath" (load)="functionAfterLoad()">
Run Code Online (Sandbox Code Playgroud)
https://stackblitz.com/edit/rotate-image-bdqndf?file=app/app.component.ts