Reputation: 3
How to share the data from Parent Component to Multiple Child components in Angular ?
Upvotes: 0
Views: 1215
Reputation: 166
You can also use Subject and subscribe to it from multiple components.
Parent Component
constructor(private event:serviceFile){}
eventSubscriber:Subscription|any;
data:any; //<- data that you want to send to child component
ngOnInit(){
this.event.sendDataToChildComponent(data); //<- Function inside service
}
ServiceFile
subjectName = new Subject<any>();
sendDataToChildComponent(data:any){
this.subjectName(data).next();
}
Child Component
constructor(private event:serviceFile){}
eventSubscriber:Subscription|any;
ngOnInit(){
this.event.subjectName.subscribe((data:any)=>{
console.log(data)
}
}
ngOnDestroy(){
if(this.eventSubscriber)this.eventSubscriber.unsubscribe();
}
Upvotes: 0
Reputation: 517
All child components get their data from parent through @Input decorator. Declaring a variable with the decorator in the child allows you to pass values from parent in the HTML template.
You can find more about it in the doc: https://angular.io/guide/inputs-outputs
And also you could send data back to parent through @Output decorator (events).
Upvotes: 0
Reputation: 44
You can create a service use that service to share the data with any component you like or a better approach will be to use @Input() in you child components to receive data from its parent component
Upvotes: 0