angular4,angular6 父组件异步获取数据传值子组件 undefined 问题

通过输入和输出属性 实现数据在父子组件的交互
在子组件内部使用@input接受父组件传入数据,使用@output传出数据到父组件
详细标准讲解参考官方文档
https://angular.cn/guide/component-interaction#pass-data-from-parent-to-child-with-input-binding

但是我在开发中遇到这样一个问题,当父组件传入的数据是在网络请求回来之后才被赋值,这时的子组件已经初始化结束,就会存在异步的问题
解决办法是使用ngOnChanges()来截听输入属性值的变化,然后在自己的代码里处理数据;

代码如下:
父组件使用子组件代码 parent传入child传出

父: html

<child-app [parent]="parent" (child)="getChild($event)"></child-app>

父:ts

getChild(child) {
    //子组件返回数据
    console.log(child)
}

子:ts

@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);

猜你喜欢

转载自www.cnblogs.com/fuzitu/p/9172728.html