首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >子组件引用父组件时的角NG3003错误

子组件引用父组件时的角NG3003错误
EN

Stack Overflow用户
提问于 2021-07-09 19:29:59
回答 2查看 582关注 0票数 0

考虑以下情况:父组件在其模板中使用子组件,子组件对注入到其子组件的父组件具有引用。

parent.component.html:

代码语言:javascript
复制
<child></child>

child.component.ts:

代码语言:javascript
复制
import { ParentComponent } from '../parent/parent.component.ts'

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

在用推荐的部分编译模式编译的库中使用此设置时,编译器将抛出NG3003错误。ideas文档提供了以下解决问题的思路:

  1. 尝试重新安排您的依赖关系,以避免循环。例如,使用存储在独立文件中的中间接口,该文件可以导入到两个依赖文件中,而不会导致导入周期。
代码语言:javascript
复制
- Using an interface in the child component to reference the parent component is not possible because the injector would not know what to inject.
  1. 将相互引用的类移动到同一个文件中,以避免它们之间的任何导入。
代码语言:javascript
复制
- I just don't want to do this. :)
  1. 如果导入的声明仅用作类型,则将导入语句转换为只导入类型的导入(使用导入类型语法),因为只有类型的导入不会对周期有所贡献。
代码语言:javascript
复制
- Same issue as with an interface, the injector would not know what to inject.

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-07-09 20:15:57

在上述情况下的N3003错误可以通过使用InjectionToken来解决,如下所示:

  1. 创建一个注入令牌: parent.token.ts: 导出Component=新InjectionToken(“父组件”);
  2. 将父组件分配给注入令牌: parent.component.ts 导入{ ParentComponent }从‘.. /父/父.组件.’@组件({.提供程序:{provider: PARENT,useExisting: ParentComponent })导出类ParentComponent {}
  3. 在子组件中,要求注入器注入注入令牌,并仅按类型引用父组件: child.component.ts //只将ParentComponent作为类型导入。从‘./ ParentComponent /parent.Component.ts’导入{ParentComponent};从‘.. /parent.Token.ts’导入{ PARENT };@Component({…})导出类ChildComponent {构造函数(@Inject(父)私有父: ParentComponent) {}}
票数 1
EN

Stack Overflow用户

发布于 2022-06-30 19:17:09

到目前为止,我只找到了一个解决方案:创建接口--比如说IParentComponent --枚举子组件中使用的所有属性和方法,并由父组件实现这个接口。然后在子组件中使用@Input() parentComponent: IParentComponent。不是很好的方法,如果有很多属性/方法.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68321910

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档