简体   繁体   中英

Angular: How to prevent component template from flashing both conditional statements?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM