Angular 角度2-将对象从父组件传递到要修改的子组件
我知道将对象从父组件发送到它的子组件就像通过@input发送一样简单 在我的例子中,我需要将一个对象从父对象发送到它的子对象,并在子对象端进行更改,然后立即在父对象端查看此更改Angular 角度2-将对象从父组件传递到要修改的子组件,angular,parent-child,Angular,Parent Child,我知道将对象从父组件发送到它的子组件就像通过@input发送一样简单 在我的例子中,我需要将一个对象从父对象发送到它的子对象,并在子对象端进行更改,然后立即在父对象端查看此更改 事实上,我想把对象的引用发送给子对象,而不是它的值 这里是一个父子通信的示例,我们将在控制台中看到,从父对象传递的对象的子对象的更改值已更改 父组件: import { Component, OnChanges, SimpleChanges } from '@angular/core'; @Component({
事实上,我想把对象的引用发送给子对象,而不是它的值 这里是一个父子通信的示例,我们将在控制台中看到,从父对象传递的对象的子对象的更改值已更改 父组件:
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);
}
}
在子组件中,我们更改从父对象接收的对象,并通过以下方式发出值:
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
将对象作为
@输入传递给子对象。在子对象中对其所做的任何修改也将应用于父对象中的对象(只要“对象”不是数字、字符串或布尔值)。我已经尝试过了,但子对象的修改不会在父对象上对其进行修改。对象不应该是数字、字符串或布尔值是什么意思?请在问题中添加相关代码:如何定义对象,如何将其传递给子组件,以及如何在子组件中修改它。
Parent: receive from child, value1 changed
Parent: receive from child, value2 changed
Parent: receive from child, value1 changed
Parent: receive from child, value2 changed