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?
Got it! There are several ways to call the function () in parent component from the child component of angular 4 such as input bindings, setters, service, etc. According to my understanding, the easiest way is using the service. In this tutorial, I will share how to communicate parent and child component using router-outlets and services method.
When you need to call a function declared in the parent component from a child component, it is as easy as passing it as a prop to the child component and calling it from the child component. However, when you want to call the other way around, things can be a bit tricky.
But it is limited because the parent-child wiring must be done entirely within the parent template. The parent component itself has no access to the child. You can’t use the local variable technique if an instance of the parent component class must read or write child component values or must call child component methods.
The Child can send data to Parent by raising an event, Parent can interact with the child via local variable or Parent can call @ViewChild on the child. We will look at all those options in this article. Applies to: Angular 2 to the latest edition of i.e. Angular 8.
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.
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)
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