[英]Is Angular *ngFor rendering asynchronous?
In the code below, the line this.images = response.map( r => r.url).slice(0,10);
在下面的代码中,这行this.images = response.map( r => r.url).slice(0,10);
fills the images
array and then ngFor
renders the data in the view.填充images
数组,然后ngFor
在视图中呈现数据。 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
.之后,将调用 Jquery 函数来初始化图像滑块,但该函数需要在timeout
才能在使用ngFor
呈现 HTML 元素时暂停。
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.我认为ngFor
是同步的,这意味着当images
数组获取其数据时, ngFor
会呈现 HTML,然后ngFor
Jquery 函数。 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,
});
}
}
You pause 10ms to wait for angular to finish rendering, but of course it might take longer than that.您暂停 10 毫秒以等待 angular 完成渲染,但当然可能需要更长的时间。 On a device with weak CPU it could take even longer than on your machine so this method isn't very reliable.在 CPU 较弱的设备上,它可能比在您的机器上花费的时间更长,因此这种方法不是很可靠。
You could try executing the jquery in the ngAfterViewChecked
lifecycle hook (see https://angular.io/guide/lifecycle-hooks )您可以尝试在ngAfterViewChecked
生命周期钩子中执行 jquery(参见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.设置超时将在宏任务队列上推送回调,并将在 DOM 更新后执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.