【问题标题】:Get dimensions of an image after render finishes, in Angular在 Angular 中渲染完成后获取图像的尺寸
【发布时间】:2021-10-11 11:54:19
【问题描述】:

我正在尝试获取组件中图像的渲染大小。使用 (load) 事件,我得到了当时显示的图像大小 (pic1) 以及页面完全呈现后的“最终”大小。我想我可以使用 ngAfterViewChecked 但这意味着当唯一有意义的实例是窗口打开或调整大小时,我会不断计算该大小

【问题讨论】:

    标签: javascript angular image events


    【解决方案1】:
    • 您可以使用的另一种方法是,使用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的信息。

    【讨论】:

    • 虽然我猜这是朝着正确的方向前进,但这个实现的问题是窗口大小实际上并没有改变。当窗口调整大小时,我已经在使用这种方法来计算图像的大小,这确实有效,这就是我注意到页面首次加载时它不起作用的原因(在恢复的窗口状态下)
    【解决方案2】:

    我最终使用了一个 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);}
    

    【讨论】:

      猜你喜欢
      • 2018-05-27
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 2016-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多