Change detection not happening with async await

137 Views Asked by At

1.showing a loader until API resolvers 2. After a getting API response, setting the loader flag to false, and trying to read the div inside flag 3. Flag value is updated but dom is not refreshed, so i dont have reference to a div inside a if condition

Why dom is not refreshed here..

Code - https://stackblitz.com/edit/reactive-form-validation-angular-15-zgnf3n?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts,src%2Findex.html,src%2Fapp%2Fapp.module.ts

1

There are 1 best solutions below

2
peinearydevelopment On

A constructor shouldn't have async code in it. There are ways to get it to work, but Angular provides various lifecycle events that should be utilized instead.

ngAfterViewInit would be my recommendation here as follows:

{{ !showLoader }}
<ng-container *ngIf="!showLoader ? widget : loaderMsg"></ng-container>
<div #widget></div>

<ng-template #loaderMsg> Loading... </ng-template>
import { HttpClient } from '@angular/common/http';
import {
    AfterViewInit,
  Component,
  ElementRef,
  ViewChild,
} from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit {
  showLoader = true;
  @ViewChild('widget', { static: false }) widget: ElementRef;
  API_KEY = '{{YOUR_API_KEY}}';

  constructor(private httpClient: HttpClient) {}
  async ngAfterViewInit(): Promise<any> {
    await this.loadDashboard();
  }

  async loadDashboard() {
    this.showLoader = true;
    const isInitalDataFetched: any = await this.getValue().catch(() => {
      return false;
    });
    console.log('test', isInitalDataFetched);
    if (isInitalDataFetched) {
    } else {
      this.showLoader = false;
      // this.cdr.detectChanges();
      console.log(this.widget);
    }
    console.log('test');
    console.log(this.widget);
  }

  getValue() {
    return this.httpClient
      .get(
        `https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${this.API_KEY}`
      )
      .toPromise();
  }
}

The docs on AfterContent hooks explain that content 'children' aren't available until one of these hooks.

Stackblitz