angular - Angular 2 - 将对象从父组件传递到子组件以进行修改
问题描述
我知道将对象从父组件发送到子组件就像通过@input 发送它一样简单。
在我的情况下,我需要将一个对象从父级发送到其子级,并在子级进行更改,并立即在父级看到此更改。
事实上,我想将对象的引用发送给孩子而不是它的值。
解决方案
这是一个父子通信的示例,我们将在控制台中看到从父传递的对象的子对象的更改值发生了变化。
父组件:
import { Component, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<child [childProp]="parentProp" (childPropChange)="fromChild($event)"></child>
`
})
export class AppComponent implements OnChanges {
parentProp = {value1: "value1", value2: "value2"};
ngOnChanges(c: SimpleChanges) {
console.log('Parent changes: This doesnt happen often ', c);
}
fromChild(val) {
console.log('Parent: receive from child, ', val.value1);
console.log('Parent: receive from child, ', val.value2);
console.log('Parent: receive from child, ', this.parentProp.value1);
console.log('Parent: receive from child, ', this.parentProp.value2);
}
}
子组件:
import { Component, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'child',
template: `
<h3>Child Component with {{childProp}}</h3>
<button (click)="fire()">Talk to parent</button>
`
})
export class ChildComponent implements OnChanges {
@Input() childProp;
@Output() childPropChange = new EventEmitter<{}>();
ngOnChanges(changes: SimpleChanges) {
console.log('in child changes with: ', changes);
}
fire() {
this.childProp.value1 = "value1 changed";
this.childProp.value2 = "value2 changed";
this.childPropChange.emit(this.childProp);
}
}
在父组件中,我们有这个对象:
parentProp = {value1: "value1", value2: "value2"};
在子组件中,我们更改从父组件接收到的对象并以这种方式发出值:
this.childProp.value1 = "value1 changed";
this.childProp.value2 = "value2 changed";
this.childPropChange.emit(this.childProp);
您可以在控制台中看到此结果:
Parent: receive from child, value1 changed
Parent: receive from child, value2 changed
Parent: receive from child, value1 changed
Parent: receive from child, value2 changed
推荐阅读
- flutter - 将列表中的所有数字相加或添加变化的变量列表的替代方式颤动
- python - 无法点击使用 Selenium 的网站
- reactjs - 我想通过 react spring 制作一个切换 div 但我收到了这个错误(TypeError: Object(...) is not a function)
- javascript - 如何使用 uploadType=resumable 将文件上传到谷歌驱动器 API
- node.js - Google App Engine,在 express/react 应用中部署后缓存的 index.html
- c# - 如何在使用 IoC 时使用接口扩展 UserControl
- flutter - 在颤振中将数据从函数传递到有状态小部件时遇到问题
- keras - 如何用 Keras Dot 函数训练余弦相似度?
- python - 迭代过滤器:如何过滤多个元组的列表?
- java - 元数据提取器的示例代码正在生成“NoClassDefFoundError”