In Angular How to detect the direct parent and communicate with it?

空扰寡人 提交于 2019-12-25 09:26:52

问题


I have a child component (child.component) which can be used in two parent components :

  1. parentA.component
  2. parentB.component

In this case, it's possible to make several templates like this :

<parentA>
  <child></child>
</parentA>

<parentA>
    <parentB>
       <child></child>
    </parentB>
</parentA>

For some reasons, the child.component need to detect if the direct parent is parentB.

I used '@Inject(forwardRef(() => parentBComponent)) private _directParent:parentBComponent'

to do this:

child.component.ts

export class ChildComponent {
     ...
     constructor(@Inject(forwardRef(() => parentBComponent)) private _directParent:parentBComponent){
         console.dir(_directParent);
     }
}

But if child.component is not wrapped by parentB.component, I get this error :

"EXCEPTION: Error in http://localhost:3000/app/tests/6.html:5:8 caused by: No provider for ParentBComponent!"

What can I do ?


回答1:


For some cases, the solution is to get the variable _directParent optional thanks the decorator @Optional() :

@Inject(forwardRef(() => parentBComponent)) @Optional() private _directParent:parentBComponent

That works if you have got only two cases and in one case there is no parentBComponent. But THAT DOES NOT GET THE DIRECT PARENT, just get one parent with this component name.



来源:https://stackoverflow.com/questions/44031614/in-angular-how-to-detect-the-direct-parent-and-communicate-with-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!