【发布时间】:2021-10-11 11:54:19
【问题描述】:
我正在尝试获取组件中图像的渲染大小。使用 (load) 事件,我得到了当时显示的图像大小 (pic1) 以及页面完全呈现后的“最终”大小。我想我可以使用 ngAfterViewChecked 但这意味着当唯一有意义的实例是窗口打开或调整大小时,我会不断计算该大小
【问题讨论】:
标签: javascript angular image events
我正在尝试获取组件中图像的渲染大小。使用 (load) 事件,我得到了当时显示的图像大小 (pic1) 以及页面完全呈现后的“最终”大小。我想我可以使用 ngAfterViewChecked 但这意味着当唯一有意义的实例是窗口打开或调整大小时,我会不断计算该大小
【问题讨论】:
标签: javascript angular image events
HostListener 订阅Window: resize 事件中的更改以计算图像尺寸,如以下代码 sn-p 所示。import { HostListener } from '@angular/core';
@HostListener('window:resize', ['$event'])
// Invoke function to compute the image dimensions here
}
注意:您也可以在AfterViewInit生命周期钩子中调用该函数来计算所述图像的尺寸,而不是在load事件中。
fromEvent 监听Window: resize 事件的变化来计算图像尺寸,如下面的代码sn-p 所示。import { fromEvent } from 'rxjs';
changeSubscription$: Subscription
ngOnInit() {
this.windowResizeEventChanges$ = fromEvent(window, 'resize').subscribe(event => {
// Invoke function to compute the image dimensions here
});
}
ngOnDestroy() {
this.windowResizeEventChangesn$.unsubscribe() // Unsubscribe to stop listening the changes in Window: resize
}
阅读更多关于fromEventhere的信息。
【讨论】:
我最终使用了一个 Mutation Observer,观察属性变化,附加到包含图像的项目上。就我而言,需要一些管理,因为它不仅运行一次,而且解决了问题
ngAfterViewInit() {
this.refElement = this.appsContainer.nativeElement.querySelector('item') as HTMLElement;
const config = { attributes: true };
this.mutationObserver = new MutationObserver((mutation) => {
const target = mutation[0].target as HTMLElement;
//some code here to execute based on some conditions and to remove the observer
}
});
this.mutationObserver.observe(this.refElement, config);}
【讨论】: