Home > OS >  Some HTML elements are not showing when displayed using an ngIf?
Some HTML elements are not showing when displayed using an ngIf?

Time:10-17

I have two buttons with varying routerlinks. Each should appear differently based on the outcome of an ngIf. However, what happens is that on loading the page for the first time, neither of these buttons load until the page is refreshed (despite having loading for the page - to wait for the data to load):

<ng-container *ngIf="moduleList">

...

     <button *ngIf="!item.TrainingModuleCompleted" mat-stroked-button [routerLink]="['training-modules-content-view', item.TrainingModuleId]" class="module-view">Select</button>
     <button *ngIf="item.TrainingModuleCompleted" mat-stroked-button [routerLink]="['training-modules-content-view', item.TrainingModuleId]" class="module-view">View</button>

...

</ng-container>

As can be seen above, a different button will be shown depending on whether item.TrainingModuleCompleted is true or not. This variable is loaded with moduleList.

This is the buttons before being loaded in (on initial load):

enter image description here

This is the buttons after being loaded (after refreshing the page):

enter image description here

The ngIf is obviously being hit before the data is loaded in.. Is there a workaround to this?

CodePudding user response:

I'm guessing that if you looked in the console you would see an error during the initial load. Is it possible that item is null or undefined when the page loads? If so, you should add a null check on item like this.

*ngIf="item?.TrainingModuleCompleted"

Also, if all you swapping out is the button text, I would just do that rather than have two buttons...
{{ item?.TrainingModuleCompleted ? 'View' : 'Select' }}

CodePudding user response:

If you load your datas after a "subscribe", you can do sth like this:

dataWS.subscribe(
    (data) => {
       //Called when success
     },
    (error) => {
       //Called when error
    }
  ).add(() => {
       //load the variable you want after
  });
  • Related