简体   繁体   中英

Is Angular *ngFor rendering asynchronous?

In the code below, the line this.images = response.map( r => r.url).slice(0,10); fills the images array and then ngFor renders the data in the view. After that a Jquery function is called to init an image slider but that function needs to be inside a timeout to make a pause while the HTML elements are rendered with ngFor .

I thought ngFor was synchronous meaning that when images array gets its data then ngFor renders the HTML and after that, the Jquery function is called. But it doesn't look like that.

import { Component, VERSION } from '@angular/core';
import {HttpClient} from '@angular/common/http';

declare var $ : any;

@Component({
  selector: 'my-app',
  template: `
        <div class="galeria">
            <div *ngFor="let img of images"><img src="{{img}}" ></div>
        </div>
              `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  images= [];

  constructor(private http: HttpClient){}

  ngOnInit(){
    this.loadImages();
  }

  loadImages(){
    this.http.get('https://jsonplaceholder.typicode.com/photos')
    .subscribe((response : any[]) => {
      
          this.images = response.map( r => r.url).slice(0,10);

          setTimeout(()=> this.loadGalery(),10);
    });
  }


loadGalery(){
    $('.galeria').bxSlider({
      mode: 'fade',
      captions: false,
      slideWidth:900,
      speed:700,
      infiniteLoop: true,
      auto: true,
      pager: true,
    });
}
}

Live example Stackblitz

You pause 10ms to wait for angular to finish rendering, but of course it might take longer than that. On a device with weak CPU it could take even longer than on your machine so this method isn't very reliable.

You could try executing the jquery in the ngAfterViewChecked lifecycle hook (see https://angular.io/guide/lifecycle-hooks )

Change detection cycle has to complete before rendering is done. Set timeout is will push callback on macro task queue and will be executed after DOM has been updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM