NgFor组件没有更新

时间:2018-04-11 13:58:17

标签: angular dom

我有一个带有内部组件的循环。我正在运行一个调整大小的函数,它设置每个组件的组件大小。这一切都在加载时很有效,但在窗口调整大小时,调整大小功能仅触发列表中的最后一个组件而不是每个组件。下面是我的父母for循环。

<masonry [options]="myOptions"> 
            <div masonry-brick class="masonry-item" *ngFor="let item of (feedsList$ | async);let i = index">
                 <grid-item [item]="item" [index]="i" [listLength]="(feedsList$ | async).length"></grid-item>
            </div>
        </masonry>

下面是组件调整大小功能和调用。

 constructor() {
    window.onresize = (e) => {
        this.calculateItemSize()
    }

}

calculateItemSize() {
        const item = Math.ceil(this.index / 11);
        const groupIndex = 11 * item;
        let itemIndex = null
        if (groupIndex == 11) {
            itemIndex = this.index + 1
        } else {
            itemIndex = (this.index + 1) - (groupIndex - 11)
        }

        let dividedWidth = this.elemRef.nativeElement.parentElement.parentElement.clientWidth / 3
        let width, height

        switch (itemIndex) {
            case 2: {
                width = dividedWidth * 2 + 'px'
                height = dividedWidth * 2 + 'px'
                break;
            }
            case 4: {
                width = dividedWidth * 2 + 'px'
                height = dividedWidth + 'px'
                break;
            }
            case 7: {
                width = dividedWidth * 2 + 'px'
                height = dividedWidth * 2 + 'px'
                break;
            }
            default: {
                width = dividedWidth + 'px'
                height = dividedWidth + 'px'
                break;
            }
        }


        this.renderer.setStyle(this.elemRef.nativeElement.parentElement, 'width', width)
        this.renderer.setStyle(this.elemRef.nativeElement.parentElement, 'height', height)
    }

1 个答案:

答案 0 :(得分:2)

您的代码无法正常运行,因为您每次运行此代码时都会重新定义窗口的监听器

window.onresize = (e) => {
    this.calculateItemSize()
}

这字面意思是

  

将此函数绑定到变量window.onresize

所以是的,你的最后一个项目正在使用它,而其他项目则没有。

解决方案是在父组件中移动此代码,并使用@ViewChildren装饰器获取所有网格项,然后在所有子项中运行该函数。

相关问题