【问题标题】:How to share the data from Parent Component to Multiple Child components in Angular?如何在 Angular 中将数据从父组件共享到多个子组件?
【发布时间】:2021-08-28 07:13:35
【问题描述】:

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

【问题讨论】:

    标签: angular


    【解决方案1】:

    您还可以使用主题并从多个组件订阅它。

    父组件

    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
    }
    

    服务文件

    subjectName = new Subject<any>();
    sendDataToChildComponent(data:any){
        this.subjectName(data).next();
    }
    

    子组件

    constructor(private event:serviceFile){}
    eventSubscriber:Subscription|any;
    ngOnInit(){
       this.event.subjectName.subscribe((data:any)=>{
           console.log(data)
       }
    }
    ngOnDestroy(){
         if(this.eventSubscriber)this.eventSubscriber.unsubscribe();
    }
    

    【讨论】:

      【解决方案2】:

      所有子组件都通过@Input 装饰器从父组件获取数据。在子级中使用装饰器声明变量允许您在 HTML 模板中从父级传递值。

      您可以在文档中找到有关它的更多信息: https://angular.io/guide/inputs-outputs

      您还可以通过@Output 装饰器(事件)将数据发送回父级。

      【讨论】:

        【解决方案3】:

        您可以创建一个服务,使用该服务与您喜欢的任何组件共享数据,或者更好的方法是在您的子组件中使用 @Input() 从其父组件接收数据

        【讨论】:

          猜你喜欢
          • 2019-06-26
          • 2020-07-16
          • 2021-02-15
          • 2020-04-05
          • 2017-06-25
          • 1970-01-01
          • 2017-11-23
          • 2017-12-24
          • 1970-01-01
          相关资源
          最近更新 更多