Reputation: 667
I need to update some data in parent component by calling a function in it after an event has occurred in the child component. Here my child components are in router outlet of parent
parentComponent.html:-
<div class="row">
Parent component
</div>
<router-outlet></router-outlet>
Parentcomponent.ts:-
fetchRequestsStatus(role, user) {
if (this.userRole) {
this.dashboardService.getStatusCount(role, user).subscribe(
res => {
console.log(res)
},
err => {
console.log(err)
})
}
}
Now on a button click in the child, I need to call function fetchRequestsStatus(role, user)
by passing a parameter from the child. I have seen @input @ output decorators for sharing data but here my child component is inside the router.
How can I proceed with this?
Upvotes: 6
Views: 2939
Reputation: 46
The cleanest solution would be to create a shared service between the parent and child component, service that holds an Subject used by parent and child component.
Refer to this answer for code sample: https://stackoverflow.com/a/41989983/5620535
Make sure you use the new providedIn: 'root'
angular feature to make sure the service is only instantiated once. (singleton)
Upvotes: 1
Reputation: 3994
If you're thinking something like
<router-outlet (onButtonClick)="fetchRequestsStatus($events)"></router-outlet>
it's invalid as the child component you're thinking is a child component is actually a sibling component at runtime.
I am guessing this is your app component. So, you can have a subject in the app.service
which can be an observer for the child and an observable for the parent.
Upvotes: 2