In angular 1.x, we could reference the parent controller by requiring this inside a directive. However, with the whole naming switch-over in angular 2, I cannot really seem to find an equivalent of that functionality?
Things I have tried so far:
I don't know Angular1 well therefore I can't tell what require
does exactly or for what purposes it is used.
To the bullets mentioned in your question:
parent template
<child [childInput]="parentValue" (childOutput)="doSomethingInParent()">
This DI behavior prevents conflicts like you mentioned in your question.
<child1 [child1Input]="child2.child2Prop"
(child1Output)="child2doSomethingInChild2()">
<child2 #child2></child2>
constructor(@Host() private parent:ParentComponent) {}
This might especially be handy in recursive components (like tree) where it's know what the parent is. In this case additional decorators might be necessary
constructor(@Optional() @SkipSelf() @Host() private parent:ParentComponent) {}
Where
@Optional()
is for the root component to avoid an exception because there is no parent of the same type to be injected@SkipSelf()
avoids the component itself to get injected when it's the same type as the parent it actually wants to get injected. DI always starts on the component itself to look up providers.See also Inject parent component of the same type as child component
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With