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