Angular 2-当* ngFor完成父组件上的调用函数时 [英] Angular 2 - when *ngFor completes call function on parent component
问题描述
我正在尝试为Angular 2应用程序创建轮播组件.
I am trying to create a carousel component for my Angular 2 application.
我希望轮播是通用的,这样它就可以支持这两种情况:
I want the carousel to be generic, so that it will support both these cases:
<myCarousel>
<div>first card</div>
<div>second card</div>
....
</myCarousel>
更通用的
<myCarousel>
<myCard *ngFor="let card of cards" [card]="card"></myCard>
</myCarousel>
问题在于,轮播组件需要在* ngFor完成之后 进行初始化,否则将无法正确显示.
The problem is that the carousel component requires an initialisation to run after the *ngFor has completed, otherwise it won't be displayed correctly.
由于数据来自Web服务调用,因此我无法猜测确切的时间安排,但是我需要轮播组件来隐式或显式地观察* ngFor完成时的情况.有人可以帮忙吗?谢谢!
Since the data is coming from a web service call, I can't guess the exact timing, but I need the carousel component to observe, implicitly or explicitly, when *ngFor has completed. Can anybody help? Thank you!
推荐答案
还有另一个Stackoverflow答案已经解决了这个问题: https://stackoverflow.com/a/36750875/463893
There is another Stackoverflow answer that already solves the problem: https://stackoverflow.com/a/36750875/463893
我的解决方案非常相似:一个指令(称为CarouselItem)应用于* ngFor内的carousel元素,定义了一个布尔输入,以告知该元素是否为最后一个,以及一个属性(或eventemitter)可以设置为当到达最后一个元素时要调用的函数.
My solution is very similar: a directive (called CarouselItem) applied to the carousel elements inside the *ngFor, defining a boolean input that tells whether the element is the last, and a property (or eventemitter) that can be set to a function to call when the last element has been reached.
因此模板变为:
<myCarousel #carousel>
<myCard *ngFor="let card of cards; let l = last"
[card]="card"
CarouselItem
[ready]="l ? true : false"
[init]="carousel.initialize">
</myCard>
</myCarousel>
需要变量#carousel才能从myCard指令([init] ="carousel.initialize")中引用轮播组件.
the variable #carousel is needed to be able to reference the carousel component from the myCard directive ( [init]="carousel.initialize" ).
以下是指令的代码:
@Directive({
selector: `[CarouselItem]`
})
export class CarouselItem {
@Input('init') onInit: Function = () => {};
@Input() set ready(isReady: boolean) {
if (isReady)
setTimeout(()=>this.onInit(), 200);
};
}
最后,轮播组件包含一个公共的初始化方法.
And finally the carousel component contains a public initialization method.
public initialize= ()=> {
// perform initialisation
};
这篇关于Angular 2-当* ngFor完成父组件上的调用函数时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!