Reputation: 1800
My application has one parent component and two sibling components.
<feed>
<status></status>
<post></post>
</feed>
what i'm trying to achieve is when i write something in status component which is basically a text field and submit , i should pass that data into post component and invoke another function in post component to update its view. But i have no idea how to accomplish this. Any help would be greatly appreciated.
Upvotes: 3
Views: 3078
Reputation: 4335
You need to implement a service and have an event emitter, you can than inject that service into both the components and emit from status
component and listen to it in post
component
common.service.ts :
@Output() public somethingChanged: EventEmitter<any> = new EventEmitter();
status.component.ts :
someFunc() {
this.commonService.somethingChanged.emit({
data: "Dummy Data For Post Component"
})
}
post.component.ts :
constructor(
public commonService: CommonService
) {
this.commonService.somethingChanged.subscribe((data: any) => {
console.log("Data from status component", data);
})
}
Now whenever someFunc
in status component will be called, the listener in post component will be executed. You need to ensure that both the components share the same instance of CommonService
i.e both status
and post
component are part of same NgModule
, if they aren't than you would need to create singleton of CommonService
using shared module with forRoot
.
Upvotes: 7