Reputation: 3229
I use Angular 10 and I have a ParentComponent, and a ChildComponent. The ChildComponent has an @Input
to members of the parent.
Due to a promise, it takes a while until the members of the parent are generated. I use this.cd.detectChanges()
later to inform the child to redraw.
How can I now update some members of my child component? Is there an observer or subscriber pattern to these changes? What would be the correct approach?
Upvotes: 0
Views: 356
Reputation: 825
You can implement ngOnChanges
life cycle method to detect change whenever an @Input
binding value changes.
ngOnChanges(changes: SimpleChanges) {
if(changes.input_var.currentValue != changes.input_var.previousValue) {
/* write your code here */
}
}
Upvotes: 2
Reputation: 3571
Instead of using detectChanges
, use the async
pipe to provide the result of the Promise:
<app-my-child-component [myInput]="myPromise$ | async">
If your Promise returns an array of images you wish to display, I would advise the following:
<ng-container *ngIf="myPromise$ | async as images">
<img *ngFor="let image of images" [src]="image">
</ng-container>
The ng-container
gives you a hook for the *ngIf
directive and allows you to create the images
alias (an Angular best practice for dealing with Observables and Promises). You then use *ngFor
to loop through the aliased returned array to display your images.
Upvotes: 1