Angular ng303 中的递归组件

问题描述 投票:0回答:1

我有两个组件,它们以某种方式相互引用。这是一个简化的示例。

@Component({
  selector: 'a',
  template: ` elements: <b /> `,
})
export class a {}

@Component({
  selector: 'b',
  template: `
    @switch (type) {
      @case (a) {
        <a />
      }
      @case (c) {
        <c />
      }
    }
  `,
})
export class b {}

我在这里收到 NG303(循环导入)错误。我完全理解为什么。 但我该如何解决这样的问题呢?

  • 解决诸如实现接口之类的问题的正常模式在这里不起作用,因为它是模板代码而不是打字稿。
  • 使用 Ivy Full build 来解决问题也是没有选择的。
angular
1个回答
0
投票

您可以创建一个公共模块并将该模块导入到这些组件的父级中,这样您就能够消除错误。但请注意,由于无限递归,示例将给出最大调用堆栈错误。

import { Component, NgModule } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { a, c } from './comps';

@Component({
  selector: 'b',
  template: `
    @switch (type) {
      @case ('a') {
        @defer (on immediate) {
        <a></a>
        } @error {
          max call stack exceeeded
        }
      }
      @case ('c') {
        <c></c>
      }
    }
  `,
})
export class b {
  type = 'a';
}
@NgModule({
  declarations: [a, b, c],
  exports: [a, b, c],
})
export class SomeModule {}

@Component({
  selector: 'app-root',
  imports: [SomeModule],
  standalone: true,
  template: `
    <b></b>
  `,
})
export class App {
  name = 'Angular';
}

bootstrapApplication(App);

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.