首页 > 解决方案 > 嵌套在更多组件中的组件不会在更改组件中丢失参考

问题描述

我有 2 个带有嵌套其他组件的组件:

...
<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);
  };
}
...
<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);
  };
}

ReceivableTableComponentBacklogTableComponent具有相同的模板

...
<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没有被破坏?不,我添加ngOnDestroyCollectionComponent并且当我更改页面时调用它,但是为什么ManualAmountComponent要参考CollectionComponent我何时调用BacklogComponent?(显然,如果我在控制台中做相反的事情

BacklogComponent{...}

BacklogComponent{...}

CollectionComponent {...})

标签: angular

解决方案


因为您在两个父组件中使用相同的组件。它将具有引用,因为它在整个应用程序中保持循环。

如果您想释放先前绑定组件的引用,您需要使用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())
}

推荐阅读