Angular - Child组件在数据更改后被破坏,为什么?

时间:2016-08-30 14:14:29

标签: angular lifecycle

在数据发生变化时,我不了解儿童组件在Angular中被破坏的目的。

在这种情况下:

我有一个父组件和子组件:

parent.component.html

<div class="parent-content" (click)="toggleChild()">
   // ...
</div>
<child></child>

通过单击要切换子项的内容(子组件将通过动画显示)

parent.component.ts

我在这里订阅了我父母的sharedService数据更改......

ngOnInit () {
    let subscription = this.sharedService.myData.subscribe( (data) => {
        this.data = data;
    });
}

..以及我的孩子(实际上孩子是动态创建的组件的包装器,所以准确 - 我在我的孩子中使用sharedService)

child.component.ts

this.resolver.resolveComponent(component).then(factory => {
     let componentRef = this.childContainer.createComponent(factory);
});

隆重-child.component.ts

ngOnInit () {
    let subscription = this.sharedService.myData.subscribe( (data) => {
        this.data = data;
    });
}

现在当 myData 发生变化时(由于服务器响应),孩子会被销毁! 我失去了所有孙子的数据,因为它也被摧毁了!

我阅读了有关组件互动的here,但仍然无法确定何时会调用ngOnDestroy,因为我没有任何@Inputs ...

也许我可以将大孩子操纵的数据存储在其他地方然后被破坏,但重点是我需要这个视图保持打开为父母和大孩子更新myData。谢谢你的帮助!

更新

我注意到,孩子(孙子)分享数据实际上并不重要,但父数据的纯粹变化导致子组件的销毁(或重新初始化,因为在破坏后再次调用子构造函数)。这个问题是如何解决的?

1 个答案:

答案 0 :(得分:2)

It turned out that @GünterZöchbauer was right. My child components were inside an *ngFor at the top of my parent template which was depending on myData. Of course the *ngFor gets rerendered after a change and so did my child components. I restructed my views by pulling the child components out of the loop and placed them independently into the app while still loading them from a higher level component dynamically. Since they rely on the sharedService they still get the data properly and stay open after change. Thanks!

相关问题