我正在嘗試使用 ngIf 來隱藏組件的詳細資訊,直到設定了所需的變數。在等待時,它應該顯示加載訊息。我試過用谷歌搜索答案,結果一片空白。
組件的代碼
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;
}
組件的 HTML
<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 class="card-container" *ngFor="let d of Booking.Dates">
<Button class="card-small" (click)="SelectedDate=(d)">
{{d.publication}} - {{d.pubdate}}
</Button>
</div>
</ng-template>
<h1 *ngIf="!Booking;">Loading</h1>
<p>Print Component</p>
如您所見,代碼應該顯示一個或另一個專案,但是當使用 ng serve 運行它時,我得到了這個。

誰能看到我做錯了什么?
uj5u.com熱心網友回復:
你真的是說
<ng-template *ngIf="Booking;">
并不是
<ng-container *ngIf="Booking;">
?
uj5u.com熱心網友回復:
在 else 邏輯中,Booking 變數被賦值為空物件
} else {
this.Booking = <Booking>{};
}
所以 Booking 變數永遠為真;請添加一個邏輯來檢查 Booking 內的屬性。就像是
<ng-template *ngIf="Booking.PrintBooking">Some content goes here</ng-template>
<h1 *ngIf="!Booking.PrintBooking">Loading</h1>
同樣對于變數初始化部分,您可以使用
Booking: Booking | {};
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/414458.html
標籤:
