Angular 2 how to make child component wait for async data to be ready

后端 未结 3 1187
遇见更好的自我
遇见更好的自我 2020-12-07 12:53

I\'m passing async data from a parent component to a child component. And the child component needs to know the length of the data in order to do something.

How the

3条回答
  •  情歌与酒
    2020-12-07 13:12

    There are three ways to do this:

    1. Put an *ngIf in parent. Only render child when parent's items is ready.
    1. Separate your input getter setter in child. Then act whenever the value is set, you can use RxJS BehaviorSubject also.
    private _items = new BehaviorSubject([]);
    
    @Input() set items(value: Items[]) { 
        this._items.next(value); 
    }
    
    get items() {
       return this._items.getValue();
    }
    
    ngOnInit() {
        this._items.subscribe(x => {
           this.chunk(x);
        })
    }
    
    1. Do it during the ngOnChanges of the child. Refer to here for example. https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#onchanges

提交回复
热议问题