angular - 如何将从子组件获取的一些数据传递给另一个子组件?
问题描述
我必须先将一些数据从孩子传递给父母。之后,需要将相同的数据从该父级传递给另一个子级。
我做的第一件事是,我已经从孩子发送了一些数据给父母。但是现在我需要将这个数据从这个父母发送给另一个孩子,我该怎么做。
这三个组成部分是,
- 父母1
- 孩子1
- 孩子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() {
}
}
解决方案
有多种方法可以将数据从一个孩子传递给另一个孩子(兄弟姐妹)
- 使用共享服务
您可以拥有一个共享服务,在两个子组件中共享。在共享服务中有一个行为主题,孩子 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);
}
- 您可以通过父组件传递数据
您可以在 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>
对于您的问题,我推荐第一种方法,但是由于您已经实现了一些代码,因此第二种方法会更容易。
推荐阅读
- performance - 时间复杂度 if else
- c - 传递给函数的数组和数组参数之间的C语言区别
- python - 使用具有相同 div 的 BeautifulSoup 进行 Web 解析 - 如果在页面上找不到,则无法返回“N/A”
- java - 在杰克逊代码中打印带有 2 位数秒的时间戳
- html - 是否有将内联样式转换为 css 类的包
- node.js - useQuery 返回未定义,但在 gql 操场上返回数据
- r - randomForest 包的功能重要性
- javascript - 如何从链表显示到控制台节点
- c++ - 并行小数组比并行大数组慢?
- oracle - 带有用户配置文件和角色的 Oracle 12c 导入转储