简体   繁体   English

Angular中如何将父组件的数据共享给多个子组件?

[英]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.

相关问题 Angular 9 - 如何将文本数据数组从父组件传递到多层子组件? - Angular 9 - How to pass array of text data from parent component to multiple layers of child components? 如何以角度将多个数据从子组件传递回父组件? - How to pass multiple data back from child to parent component in angular? 如何在Angular 6中从父组件调用子组件的方法 - How to call child components's method from the parent component in Angular 6 如何在 Angular 中从父组件到子组件共享我的数据? - How can i share my data from parent to child component in Angular? 如何在父组件(Angular)中操作来自子组件的数据? - How to manipulate data coming from child component in parent component (Angular)? 如何在Angular4中将数据从子组件传递到父组件 - How to pass data from child component to parent component in Angular4 Angular:如何将数据从子组件发送到父组件? - Angular: how to send data from child component to parent component? 如何以角度将数据从父组件传递到自动完成子组件 - How to Pass data to autocomplete child component from parent component in angular 在Angular中将多个数据从父组件传递到子组件时遇到错误 - Getting error in Passing multiple data from parent to child component in Angular 如何将角度5中的点击数据从父组件传递到子组件? - How to pass data on click in angular 5 from parent component to child component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM