【发布时间】:2017-02-20 15:53:38
【问题描述】:
Angular 2 应用程序中的Masonry 网格存在一个问题。
我们需要在 DOM 准备好并加载内容后调用 masonry init。 我尝试了所有 Angular 2 生命周期事件,但它不适用于所有场景。
我们正在使用 ngrx - redux,这是我尝试实现此目的的一段代码:
在构造函数中,我从状态中获取数据
constructor(private store: Store<IAppState>) {
this.recommended$ = this.store
.select('layout')
.pluck('data');
}
在ngAfterViewInit 中,我订阅了上述数据,当它到来时,我想初始化 Masonry 网格。
ngAfterViewInit(): void {
this.recommended$
.subscribe((item: boolean) => {
if (item) {
new Masonry(this.masonryGrid.nativeElement, {});
}
});
}
其中this.masonryGrid.nativeElement 是组件模板@ViewChild('masonryGrid') masonryGrid: ElementRef; 中的div(网格)
如果我尝试打开我们直接加载砖石网格的路线,它会起作用。
但是,如果我从另一条路线来到那条路线,就会发生这种情况: http://i.prntscr.com/23583025e000490c940caeb06c695890.png
这可能是因为 DOM 没有在 ngAfterViewInit() 中呈现(在我们的例子中,图像不是)
http://i.prntscr.com/e46e87e5cf9740b6929ebe2e8635b040.png
欢迎任何建议,我们将不胜感激。
谢谢
【问题讨论】:
-
Angular 无法提供在非 Angular 组件完成渲染时触发的事件。
Masonry组件渲染同步,然后只需将代码放在if(item) {...}中,或者如果它渲染异步,则Masonry需要在完成渲染时触发一个事件。