Home > Mobile >  Neither component in an ngIf statement are being shown even though one of them should be truey
Neither component in an ngIf statement are being shown even though one of them should be truey

Time:01-19

I'm trying to use an ngIf to hide the details of a component until the required variable has been set. While it's waiting it's supposed to show a loading message. I've tried googling for the answer and have come up blank.

The code for the component

export class PrintBookingComponent implements  AfterContentInit {
  private Interface: MSLZohoInterface | undefined;

  constructor(private changeDetector: ChangeDetectorRef) {
  }
  ngAfterContentInit(): void {
    console.log("Initialising Print Booking");
    this.Interface = new MSLZohoInterface();
    var val = this.Interface.LoadBooking("4032446000000880091");
    if (val != undefined) {
      this.Booking = val;
      this.SelectedDate = this.Booking.Dates[0];
      //console.log(this.Booking);
    } else {
      this.Booking = <Booking>{};
    }
    this.HasBooking = true;
    //this.changeDetector.detectChanges();
  }
  Booking: Booking | undefined;
  HasBooking: boolean = false;
  SelectedDate: PrintDate | undefined;

}

The HTML for the component

<ng-template *ngIf="Booking;">
  <H1>{{Booking.PrintBooking.Sales_Order.display_value}}</H1>
  <h2>{{Booking.PrintBooking.Account.display_value}} - {{Booking.PrintBooking.ContactID.display_value}}</h2>

  <div  *ngFor="let d of Booking.Dates">
    <Button  (click)="SelectedDate=(d)">
      {{d.publication}} - {{d.pubdate}}
    </Button>
  </div>
</ng-template>
<h1 *ngIf="!Booking;">Loading</h1>
<p>Print Component</p>

As you can see the code should be showing one or the other item, however when run it with ng serve I get this. Screen shot of screen output showing the text Print Component

Can anyone see what I'm doing wrong?

CodePudding user response:

Do you really mean

<ng-template *ngIf="Booking;">

and not

<ng-container *ngIf="Booking;">

?

CodePudding user response:

In the else logic Booking variable is assigned empty object

} else {
  this.Booking = <Booking>{};
}

So the Booking variable will always be true; Kindly add a logic to check property inside Booking. something like

<ng-template *ngIf="Booking.PrintBooking">Some content goes here</ng-template>
<h1 *ngIf="!Booking.PrintBooking">Loading</h1>

Also for variable initialisation part you can use

Booking: Booking | {};
  •  Tags:  
  • Related