Angular子组件引用父组件时出现NG3003错误

Angular NG3003 error when child component references parent component

考虑以下情况:一个父组件在它的模板中使用了一个子组件,子组件有一个对父组件的引用被注入其中。

parent.component.html:

<child></child>

child.component.ts:

import { ParentComponent } from '../parent/parent.component.ts'

@Component({ 
  selector: 'child'
  ... 
})
export class ChildComponent {
  
  constructor(private parent: ParentComponent) { }
}

在使用推荐 partial compilation mode, the compiler throws the NG3003 error 编译的库中使用此设置时。 Angular 文档提供了以下解决问题的方法:

  1. Try to re-arrange your dependencies to avoid the cycle. For example using an intermediate interface that is stored in an independent file that can be imported to both dependent files without causing an import cycle.

    • 无法使用子组件中的接口来引用父组件,因为注入器不知道要注入什么。
  2. Move the classes that reference each other into the same file, to avoid any imports between them.

    • 我只是不想这样做。 :)
  3. Convert import statements to type-only imports (using import type syntax) if the imported declarations are only used as types, as type-only imports do not contribute to cycles.

    • 与接口相同的问题,注入器不知道要注入什么。

是否有另一种方法可以解决 N3003 错误而不将父组件和子组件移动到同一文件中?

所描述情况下的 N3003 错误可以使用 InjectionToken 解决,如下所示:

  1. 创建注入令牌:

    parent.token.ts:

    export const PARENT = new InjectionToken('Parent Component');
    
  2. 将父组件分配给注入令牌:

    parent.component.ts

    import { ParentComponent } from '../parent/parent.component.ts'
    
    @Component({ 
      ...
      provider:[{
        provide: PARENT,
        useExisting: ParentComponent 
      }]
    })
    export class ParentComponent { }
    
  3. 在子组件中,让注入器注入注入令牌,仅按类型引用父组件:

    child.component.ts

    // Import ParentComponent as a type only.
    import type { ParentComponent } from '../parent/parent.component.ts';
    import { PARENT } from '../parent/parent.token.ts';
    
    @Component({ ... })
    export class ChildComponent {
    
      constructor(@Inject(PARENT) private parent: ParentComponent) { }
    }