If I have multiple levels of angular components, how can I use @Output
to emit an event from child to the grand parent?
Grandparent:
<parent (handleClick)="grandmaHandleClick($event)">
<parent>
...
grandmaHandleClick(event) {
console.log('grandma knows you clicked')
}
Parent:
<child (handleClick)="handleClick($event)">
</child>
Child:
<div (click)="onClick()">Click button
</div>
...
@Output() handleClick = new EventEmitter
onClick() {
this.handleClick.emit('clicked a button')
}
I am trying to have it so that @Output can prop drill a few components deep, whats the best way to accomplish this, and can you provide example?
Best Answer
There could be 2 ways:
@output
:Grandparent
Parent:
Child is implemented properly in the code so it is good to go.
BehaviorSubject
viaService
: With this much level of nesting, you can actually create some service likeEventService
, and then createBehaviorSubject
which can directly be subscribed by the GrandParent. Also, to make thisservice
more component specific, you can keep this service in amodule
which will have other 3 components (GrandParent, Parent and Child)and then in
components
:ChildComponent
GrandParent
Please note that, with
@output
event, you create a tight coupling of components and so a strong dependency (parent-child-grandchild) is created. If the component are not reusable and are only created to serve this purpose, then@output
will also make sense because it'll convey the message to any new developer that they have parent-child relationship.Creating a service to pass data also exposes the data to other components which can inject
service
inconstructor
.So, the decision should be taken accordingly.