Retrieve elements created by ngFor in ngAfterViewInit

后端 未结 2 1681
青春惊慌失措
青春惊慌失措 2020-12-21 03:39

I\'m implementing a lazy image loader in my Angular (5) app, and am curious how I can avoid having to call setTimeout() in my ngAfterViewInit(), if

2条回答
  •  盖世英雄少女心
    2020-12-21 04:04

    You can use the requesAnimationFrame API.

    Your problem is that even though Angular told the browser to render the images, they are not rendered yet, it takes some times for it to do so and update the DOM, that's why your array is empty.

    The requestAnimationFrame API asks for the browser to tell you (via a callback method) when it's done with it's current tasks, when rendering is complete.

    ngAfterViewInit(): void {
      window.requestAnimationFrame(() => {
        //place your code here
      })
    }
    

提交回复
热议问题