When I have a component that needs to display a spinner during an operation, I came across an issue:
This is the HTML code snippet:
<spinner *ngIf='isLoading'></spinner>
<xx-table
(onSort)='onSort()'>
</xx-table>
This is the TypeScript code of the component:
onSort(): void {
this.isLoading = true;
// The operation takes about 1 second
this.isLoading = false;
}
Although I explicitly set this.isLoading
to true, the change is not reflected in the template. It seems like the change detection is only triggered after the onSort()
method finishes executing. If I remove the line this.isLoading = false;
, the spinner shows up and remains there for approximately 1 second before disappearing.
How can I make sure this change is visible while the method is still running? And what exactly is the mechanism behind this behavior?
(I am aware that I can trigger change detection manually, but I'm curious why this change is not automatically detected.)