Hello everyone, in this article we are going to implement a loading spinner in Angular 8. If your app has a back end then in order to give your users feedback while the data is fetched, it is of utmost importance.
There are tons of options available which can be integrated but for the demo purpose today we will use two methods. Firstly, we will use the progress spinner provided by Angular Material and then one using third party ngx-spinner
We will use the setTimeout() method to replicate a HTTP request or any other operation which might take some time to finish.
Setting Up the Angular 8 App
We will first create a new app using Angular CLI named loader-demo and implement are fake back-end in the app.component.ts file.
- Boolean variable showLoader will reflect if the loader will is visible or not
- In our FakeBackendService() method we first set the showLoader to true, indicating show the loader
- Using the setTimeout method we wait for 5 sec and then hide the loader and display the message that “Data retrieved from back end”.
- We hook our FakeBackendService() method to the click event of the button
- The data from service will be displayed on screen once the service brings the response after 5 seconds.
Implement the Loading Spinner
Using Angular Material Progress Spinner
- Let us first add Angular Material into our project. Refer here to use Angular CLI for the same.
- Import MatProgressSpinnerModule into your app.module.ts file and then update the app.component.html file to have the spinner added.
- We will use the *ngIf directive so that the <mat-spinner> div will be only show when the showLoader is set to true
- [diameter] is used to determine the size of the loader.
- When we click on the button our loading spinner will appear and will stay there for 5 seconds post which it will disappear and our data will be loaded.
Also Read: Hostlistener and Hostbinding in Angular
- Add ngx-spinner into the project using the following command: npm install ngx-spinner
- Import NgxSpinnerModule in the app.module.ts file
- NgxSpinnerService is used as a service, hence it needs to be injected in the app.component.ts
- We will show and hide the spinner in the same function using the variable ngxShowLoader and its Show and Hide method
We have used these two specifically because of their default output. ngx-spinner loads in the center of screen and also disables the other parts of the UI till the time it is visible.