下面是一个父子通信的示例,我们将在控制台中看到,从父对象传递的子对象的已更改值已更改。
父组件:
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 stackblidtz
在父组件中,我们有以下对象:
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