angular 父组件异步获取数据后传值给子组件

参考: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++;
});

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值