Take a look at this example I created on stackblitz: link
In this example, I have set up an Angular Material spinner and a tag where API results can be displayed in my template:
<button (click)="onFetch()" >Click me to send request</button>
<mat-spinner *ngIf="spin"></mat-spinner>
<p *ngIf="!spin">{{result}}</p>
The button triggers the request to the API.
As shown in the template, there is an ngIf condition for both the spinner and the result tag, to toggle between showing either the spinner or the result.
Upon clicking the button, the onFetch
function is executed which displays the spinner by setting this.spin = true
.
onFetch() {
this.spin = true
ajax.getJSON(this.url)
.pipe(
delay(1000)
)
.subscribe(json => {
this.spin = false
this.result = json.value
})
}
When the request completes and returns a result, this.spin = false
is triggered, making the spinner disappear.