using setTimeout to reload child component instead of ngOnChanges inside it

Published

Maybe for someone, this question will sound a little dumb. For me, is an unexpected behavior because I reuse a child component and I found that the data inside it are not updated when I change the source from parent. Because I don’t want to implement ngOnChanges there (I try to avoid using it how much I can), an idea appear in my mind: use a boolean to hide and render the template again. But because the process is too fast, this will not emit. So, I need to use a setTimeout there (100ms are enough). But is this approach ok? This is my question. I tried to use changeDetectionRef, but still don’t work, because inside the child component, all the logic are inside ngOnInit method, so will be fired only when the component is initialized.

<ng-container
   *ngIf="selectedView && !reloadChart"
   [ngSwitch]="selectedView.chartType">
   <app-line-chart
       *ngSwitchCase="'line'"
       [data]="selectedView.data"
       fxFlex="100"></app-line-chart>
   <app-pie-chart
       *ngSwitchCase="'pie'"
       [data]="selectedView.data"
       fxFlex="100"></app-pie-chart>
   <fa-icon style="position: absolute; top: 4px; left: 4px;"
       class="views__item__ok"
       [icon]="faCheck"
       (click)="selectView(view)"
       size="2x"></fa-icon>
</ng-container>

Because selectedView get same chartType, it will not update the chart data, so inside the selectView method, I added timeout:

selectView(view: View): void {
    this.reloadChart = true;
    this.widget.viewId = view.id;
    this.widget.requestType = view.requestType;
    this.selectedView = view;

    // stuff

    // this will force to render again the child component, 
    // because for 100ms, the reloadChart field will be true
    setTimeout(() => {
      this.reloadChart = false; 
      this.cd.detectChanges();
    }, 100);
}

Inside visualization panel is the problem (code displayed above). When I select one of the widgets from the carousel, it will change the child component to selectedWidget.chartType (app-pie-chart, app-line-chart, app-table-widget). The problem is when previous chart have same type as current chart, because inside the [ngSwitch] will remain same case. I don’t want to modify the child component, but want to render it again inside the parent.

image

Source: Angular Questions

Published
Categorized as angular, javascript, settimeout, typescript Tagged , , ,

Answers

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq