angular - 嵌套在更多组件中的组件不会在更改组件中丢失参考
问题描述
我有 2 个带有嵌套其他组件的组件:
BacklogComponent
...
<backlog-table>
<ng-container expandedDetail>
<manual-amount [maxValueFunction]="maxValue()"></manual-amount>
</ng-container>
</backlog-table>
...
maxValue() {
return (entity) => {
console.log(this); // added for debug
return subNumbers(entity.financeable, entity.financed);
};
}
CollectionComponent
...
<receivable-table>
<ng-container expandedDetail>
<manual-amount [maxValueFunction]="maxValue()"></manual-amount>
</ng-container>
</receivable-table>
...
maxValue() {
return (entity) => {
return reconcileElement(entity.outstanding, entity.collected, entity.amount, entity.total);
};
}
ReceivableTableComponent
并BacklogTableComponent
具有相同的模板
...
<ng-content select="[expandedDetail]"></ng-content>
...
ManualAmountComponent implements OnInit
和:
ngOnInit() {
this.expandedDetailService.entity$
.subscribe((gotEntity: T) => {
if (gotEntity) {
this.element = gotEntity;
this.maxValue = this.maxValueFunction(this.element);
}
});
}
现在,启动的应用程序,我去链接CollectionComponent
和控制台有
CollectionComponent {...}
然后我更改页面并转到BacklogComponent
。在控制台中添加
CollectionComponent {...}
BacklogComponent{...}
为什么我的组件CollectionComponent
没有被破坏?不,我添加ngOnDestroy
到CollectionComponent
并且当我更改页面时调用它,但是为什么ManualAmountComponent
要参考CollectionComponent
我何时调用BacklogComponent
?(显然,如果我在控制台中做相反的事情
BacklogComponent{...}
BacklogComponent{...}
CollectionComponent {...}
)
解决方案
因为您在两个父组件中使用相同的组件。它将具有引用,因为它在整个应用程序中保持循环。
如果您想释放先前绑定组件的引用,您需要使用ngOnDestroy
中的方法ManualAmountComponent
来重置您想要重新初始化的所有值。
在这里,当您订阅服务时,ManualAmountComponent
您也需要unsubscribe()
它。
因此,您需要在嵌套组件中维护订阅数组,如下所示。
subscriptions:Subscription[]=[]
ngOnInit() {
this.subscriptions.push(this.expandedDetailService.entity$
.subscribe((gotEntity: T) => {
if (gotEntity) {
this.element = gotEntity;
this.maxValue = this.maxValueFunction(this.element);
}
});
)
}
ngOnDestroy(){
this.subscriptions.forEach((subscription)=>subscription.unSubscribe())
}
推荐阅读
- javascript - ReferenceError:在 express.js 中使用 mergeImages 时未定义窗口
- linux - netns:从另一个命名空间的默认命名空间执行命令
- git - git branch rebase 通用约定
- r - 我正在尝试检索与特定列中的内容相等的行
- android - 如何为 MDM 分发构建移动应用程序
- pandas - 使用 pandas 将带有月份名称的日期格式转换为正确的日期
- flutter - Flutter 异常:在 null 上调用了 getter 'latitude'。接收方:null 尝试呼叫:纬度
- css - 屏幕尺寸减小时如何将导航图像居中对齐
- linux - Doas 一直要求我输入密码
- codeigniter - 获取总金额并将其存储在另一张桌子上。(代码点火器)