参考:https://www.cnblogs.com/fuzitu/p/9172728.html
https://www.it1352.com/1551144.html
通过输入和输出属性 实现数据在父子组件的交互
在子组件内部使用@input接受父组件传入数据,使用@output传出数据到父组件
详细标准讲解参考官方文档
https://angular.cn/guide/component-interaction#pass-data-from-parent-to-child-with-input-binding
但是我在开发中遇到这样一个问题,当父组件传入的数据是在网络请求回来之后才被赋值,这时的子组件已经初始化结束,就会存在异步的问题
解决办法是使用ngOnChanges()来截听输入属性值的变化,然后在自己的代码里处理数据;
代码如下:
父组件使用子组件代码 parent传入child传出
父:
<child-app [parent]="parent" (child)="getChild($event)"></child-app>
父:
getChild(child) {
//子组件返回数据
console.log(child)
}
子:
@Component({
selector: 'child-appt',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
@Input() parent: any;
@Output() child = new EventEmitter<any>()
ngOnChanges(changes: SimpleChanges): void {
if (changes['parent'] !== undefined) {
this.curParent = changes['parent'].currentValue;
}
}
this.child.emit(data);
另一个答案:
I have a child component that contains complex input (some chart data). I am sending this chart data from the parent component through the @Input() decorator in Angular 5 after getting API response. So, I need to sync the chart according with the API response every time it gets changed on the parent component, hence, the OnChange Lifecyle. But unfortunately, I am not able to get this to work properly. I tried with setting a dummy input field with basic number type and increment it but in vain. Here's my implementation:
Child chart component:
export class ChartComponent implements OnInit, OnChanges {
@Input() chartData;
@Input() triggerChart;
ngOnChanges(changes: SimpleChanges) {
console.log(changes);
}
}
Parent component html:
<app-chart [chartData]="chartData" [triggerChart]="triggerChartData"></app-chart>
<input [(ngModel)]="triggerChartData" type="hidden">
Parent component:
this.chartService.getChartData(params).subscribe(res => {
this.chartData = res;
this.triggerChartData++;
});