Angular 与 "russian dolls" 个组件的循环依赖

Angular circular dependency with "russian dolls" components

我们构建了一个通用的主从组件,它将根据提供的 @Input EntityType 属性 呈现特定的详细信息组件。 在主细节组件模板中,我们调用一个 wrapper/factory 组件,它将根据实体类型呈现适当的细节组件:

@Component({
  selector: 'master-detail',
  template: `
    <div>
      <grid></grid>
      <detail-wrapper> [entityType]=entityType></detail-wrapper>
    </div>
  `,
})
export class MasterDetailComponent {
  @Input() entityType: string ;
  ...
}

@Component({
  selector: 'detail-wrapper',
  template: `
    <ng-container [ngSwitch]="entityType">
      <comp-a *ngSwitchCase="'A'"></comp-a>
      <comp-b *ngSwitchCase="'B'""></comp-b>
      <comp-default *ngSwitchDefault></comp-default>
    </ng-container>
  `,
})
export class DetailWrapperComponent {
  @Input() entityType: string ;
  ...
}

细节组件本身可以包含另一个主从组件(如俄罗斯套娃)。但是,当发生这种情况时,我的代码不会 运行 因为循环依赖:

master-detail -> detail-wrapper -> compA -> master-detail

我知道我可以通过使用继承为每个级别创建重复项来打破循环依赖:

export class MasterDetailLevel2Component extends MasterDetailComponent {...}
export class CompALevel2Component extends CompAComponent {...}

但这看起来确实不是一个合适的解决方案,需要为每个递归级别创建 类。

我看到的另一种可能性是使用 ComponentFactoryResolver 而不是 DetailWrapperComponent。然后将为 MasterDetailComponent 提供组件工厂接口(因此删除具体实现之间的链接)。但是有了这个解决方案,我就失去了模板绑定。

有没有更好的方法来解决这个问题?

我找到的最佳解决方案是在我的主从组件中使用@ContentChild,并让它注入来自父组件的详细信息模板。这样我就摆脱了循环依赖,也让我的组件更加灵活。这是一篇关于此的非常好的文章:

https://blog.jonrshar.pe/2017/May/29/angular-ng-template-outlet.html