I'm trying to stop my component template from flashing both conditional statements when the condition changes after the component is initialized.
My application receive a token and according to it's validity it displays the necessary content in the template. The problem is that the token is send to an API and until it responds the component is already initialized thus taking the default boolean value. In case the token is valid the the boolean is true thus the template showing both conditional statements for a second and then hiding the else statement.
// template.html
<ng-container *ngIf="isTokenValid; else tokenIsInvalid">
Token is valid content...
</ng-container>
<ng-template #tokenIsInvalid>
Token is invalid content...
</ng-template>
// component.ts
...
isTokenValid: boolean = false; // Initialized to false by default
...
ngOnInit(){
// Subscribe to the auth service to validate the provided token
this.authService.validateToken(token).subscribe((res: any) => {
if (res.success) { // If the API call was successful
this.isTokenValid = true; // The token is valid so we change the boolean
...
}
});
}
The desired result is the component template to wait until the API call is done and then display the correct content according to the final boolean value.
I use this pattern for a lot of my projects
ts:
loading: boolean = false;
ngOnInit() {
loading = true;
// do something
// when finished doing something
loading = false;
}
html:
<div *ngif="!loading">
<!-- wrap around content -->
</div>
I also use a loading icon that displays when loading is happening... so that the user isn't curious why there is nothing showing... does that help? if not let me know.