Search code examples
angulartypescriptangular-materialngoninit

Angular Material tab navigates to selected tab after ngOnInit


I want to to navigate to new tabs and show loading spinner until search component gets data from api to display.

But tab navigates to selected item only after component has been loaded. Is there any way to change that?

If not how can I fire code block which I have inside `ngOnInit()' once the component is loaded

I have function to execute in search component which returns data. I want to display a spinner until data is available to display.

export class SearchComponent implements OnInit {
isLoading= true;
  constructor() { }

  ngOnInit() {
    console.log('loaded');
    // api call here to get data
    //show spinner untill we get response from api
    this.isLoading = false;
  }

}
<mat-spinner *ngIf="isLoading"></mat-spinner>

But now since I have it inside Oninit() tab navigates to search only after data is available. So there is a delay of 4-5 secs to navigate to those tabs

Stackblitz demo


Solution

  • You might use a variable on a service that is injected into all the components. For example, a variable like isLoading.

    Check this variable on all the components or inside a parent component. If you show spinner on the parent component, you should also use the same service on the parent component. Show a spinner if it is loading.

    inside ngOnInit() you can just make

    setTimeout(() => { // do an async thing there
    }, 0);