簡體   English   中英

Angular *ngFor 渲染異步嗎?

[英]Is Angular *ngFor rendering asynchronous?

在下面的代碼中,這行this.images = response.map( r => r.url).slice(0,10); 填充images數組,然后ngFor在視圖中呈現數據。 之后,將調用 Jquery 函數來初始化圖像滑塊,但該函數需要在timeout才能在使用ngFor呈現 HTML 元素時暫停。

我認為ngFor是同步的,這意味着當images數組獲取其數據時, ngFor會呈現 HTML,然后ngFor Jquery 函數。 但它看起來不像那樣。

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,
    });
}
}

現場示例 Stackblitz

您暫停 10 毫秒以等待 angular 完成渲染,但當然可能需要更長的時間。 在 CPU 較弱的設備上,它可能比在您的機器上花費的時間更長,因此這種方法不是很可靠。

您可以嘗試在ngAfterViewChecked生命周期鈎子中執行 jquery(參見https://angular.io/guide/lifecycle-hooks

更改檢測周期必須在渲染完成之前完成。 設置超時將在宏任務隊列上推送回調,並將在 DOM 更新后執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM