首页 > 解决方案 > 如何将从子组件获取的一些数据传递给另一个子组件?

问题描述

我必须先将一些数据从孩子传递给父母。之后,需要将相同的数据从该父级传递给另一个子级。

我做的第一件事是,我已经从孩子发送了一些数据给父母。但是现在我需要将这个数据从这个父母发送给另一个孩子,我该怎么做。

这三个组成部分是,

  1. 父母1
  2. 孩子1
  3. 孩子2

子 1 组件 ts


import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child1',
  templateUrl: './child1.component.html',
  styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit {

  name:string[]
  @Output() messageEvent: EventEmitter<string[]>;
  constructor() {
    this.messageEvent = new EventEmitter<string[]>();
    // this.name = 'This msg from the child'
  }

  sendMessage(){
    this.messageEvent.emit(['shubham','shubham@gmail.com' ,'9525859898']);
  }



  ngOnInit() {
  }

}

-------------------------------------------

parent1  component ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-parent1',
  templateUrl: './parent1.component.html',
  styleUrls: ['./parent1.component.css']
})
export class Parent1Component implements OnInit {
   msg: string;
  constructor() { }
  getMessage($event){
    this.msg = $event;
  }
  ngOnInit() {
  }

}

子 2 组件 2 ts


import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-child2',
  templateUrl: './child2.component.html',
  styleUrls: ['./child2.component.css']
})
export class Child2Component implements OnInit {

  @Input() msg
  constructor() { }

  showData($event){
    this.msg = $event
  }

  ngOnInit() {
  }

}

标签: angularinputoutput

解决方案


有多种方法可以将数据从一个孩子传递给另一个孩子(兄弟姐妹)

  1. 使用共享服务

您可以拥有一个共享服务,在两个子组件中共享。在共享服务中有一个行为主题,孩子 2 可以订阅。您可以从 child1 更新行为主体,当您这样做时,child2 将收到更改。

// in your shared service,
sharedData: BehaviourSubject<any> = new BehaviourSubject();

//in your child2 component
sharedService.sharedData.subscribe(value => {
   // do something with your data
}

//in your child1 component
private changeData(data) {
   sharedService.sharedData.next(data);
}
  1. 您可以通过父组件传递数据

您可以在 child1 中使用事件发射器并从父级捕获事件。然后您可以在 child2 组件中使用@input()并将该数据从 parent 传递给 child2。您可以使用ngOnChanges生命周期挂钩来捕获更改。

// child2
export class Child2 implements onInit, onChanges {
   @Input() msg;

   ngOnChanges(changes: SimpleChanges): void {
      if(changes.msg) {
         //do something
      }
   }

}

// parent html
<child2 [msg]="data"></child2>

对于您的问题,我推荐第一种方法,但是由于您已经实现了一些代码,因此第二种方法会更容易。


推荐阅读