我正在嘗試獲取組件中影像的渲染大小。使用 (load) 事件,我獲得了當時顯示的影像大小 (pic1) 以及頁面完全呈現后的“最終”大小。我想我可以使用 ngAfterViewChecked 但這意味著當唯一有意義的實體是視窗打開或調整大小時,我會不斷計算該大小

uj5u.com熱心網友回復:
- 您可以使用的另一種方法是,使用 訂閱
Window: resize事件中的更改HostListener以計算影像尺寸,如以下代碼片段所示。
import { HostListener } from '@angular/core';
@HostListener('window:resize', ['$event'])
// Invoke function to compute the image dimensions here
}
注意:您還可以呼叫該函式來計算AfterViewInit生命周期鉤子內而不是load事件中所述影像的尺寸。
- 另一種方法是通過使用 監聽
Window: resize事件中的變化來計算影像尺寸fromEvent,如下面的代碼片段所示。
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
}
閱讀更多關于fromEvent 這里。
uj5u.com熱心網友回復:
我最終使用了 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);}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/317174.html
標籤:javascript 有角的 图片 事件
