angularangular-materialangular-material-7

Why mat-spinner not showing?


Index.html file is:

<body>
    <mat-spinner></mat-spinner>
</body>

App.module file is:

@NgModule({

 imports: [
        BrowserModule,
        AppRoutingModule,
        BrowserAnimationsModule,
        MatProgressSpinnerModule,
        BrowserAnimationsModule
]
})

I see on the page tag <mat-spinner></mat-spinner> but it does not work, no any errors in console


Solution

  • Angular components can't be rendered on their own inside the index.html file. That's why default AppComponent is bootstrapped through main.ts file.

    You should include the mat-spinner inside an Angular Component. If the spinner is meant to be displayed on application boostraping, you must use a custom spinner which can then be included in the index.html :

    <app-root><div id="spinner"></div></app-root>
    

    To display a spinner when lazy loading a module on routing, you can listen to router.events in the component containing the <router-outlet>:

    loading: boolean;
    
      constructor(private router: Router) {
        router.events.subscribe(event => {
          if (event instanceof NavigationStart) {
            this.loading = true;
          }
          if (event instanceof NavigationEnd || event instanceof NavigationError || event instanceof NavigationCancel) {
            this.loading = false;
          }
        });
      }
    

    and display conditionally your spinner :

    <mat-spinner *ngIf="loading"></mat-spinner>
    

    here is a stackblitz example (but the spinner isn't displayed as the modules are loaded too quickly) : https://stackblitz.com/edit/angular-ivy-xwd2ta?file=src%2Fapp%2Fapp.component.ts