[英]How to share the data from Parent Component to Multiple Child components in Angular?
How to share the data from Parent Component to Multiple Child components in Angular? Angular中如何将父组件的数据共享给多个子组件?
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您可以创建一个服务,使用该服务与您喜欢的任何组件共享数据,或者更好的方法是在子组件中使用 @Input() 从其父组件接收数据
All child components get their data from parent through @Input decorator.所有子组件都通过 @Input 装饰器从父组件获取数据。 Declaring a variable with the decorator in the child allows you to pass values from parent in the HTML template.使用子中的装饰器声明变量允许您在 HTML 模板中从父级传递值。
You can find more about it in the doc: https://angular.io/guide/inputs-outputs您可以在文档中找到有关它的更多信息: https://angular.io/guide/inputs-outputs
And also you could send data back to parent through @Output decorator (events).您还可以通过 @Output 装饰器(事件)将数据发送回父级。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.