Inject parent component of the same type as child component

前端 未结 3 1923
走了就别回头了
走了就别回头了 2020-12-14 23:22

In Angular 2, a child component can get its parent component injected through a constructor parameter. Example:

@Component({...})
export class ParentComponen         


        
3条回答
  •  情话喂你
    2020-12-14 23:52

    Angular2 looks into the current injector for a provider. In your case, TreeNodeComponent corresponds to the component itself.

    The parent component instance is located into the parent injector.

    I think that you could try to inject an Injector class to have access to the parent injector and then get the instance of the parent component. Something like that:

    @Component({
      (...)
    })
    export class TreeNodeComponent {
      constructor(injector:Injector) {
        let parentInjector = injector.parent;
        let parent = patentInjector.get(TreeNodeComponent);
      }
    }
    

    See this link for the documentation of the Injector class:

    • https://angular.io/docs/ts/latest/api/core/Injector-class.html

    That said, I think that the Gunter's comment about binding and shared service is particularly relevant...

提交回复
热议问题