问题
I have a child component (child.component) which can be used in two parent components :
- parentA.component
- 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