[英]Angular - *ngIf not evaluating
我正在嘗試解決問題並編寫以下代碼以查看發生了什么,但現在我更加困惑。 理想情況下,如果entry.customer
有值應該打印,然后也應該顯示Hello
,否則應該顯示NOPE
和Goodbye
,但實際結果是只顯示entry.customer
的值。
<h3>{{entry.customer}}</h3>
<span *ngIf="entry.customer else no">
<h1>Hello</h1>
</span>
<ng-template #no>
<h1> NOPE</h1>
</ng-template>
<span *ngIf="!entry.customer">
<h1>Goodbye</h1>
</span>
<h3> {{entry.customer}} </h3>
<span *ngIf="entry.customer else no">
<h1>Hello</h1>
</span>
<ng-template #no>
<h1> NOPE</h1>
</ng-template>
<span *ngIf="!entry.customer">
<h1>Goodbye</h1>
</span>
當我開始追蹤這個問題時,我認為由於條目的值來自 BehaviorSubject,可能存在更改檢測問題,因此我嘗試獲取區域中的值,但這並沒有改變結果。
ngOnInit(): void {
this.ngZone.run(() => {
debugger;
this._entryService.entry.subscribe(entry => {
debugger;
this.entry = entry;
});
})
}
誰能解釋 *ngIf 不起作用的可能原因,但使用花括號確實顯示了該值? 如果它有幫助,我正在使用的任何組件是從獲取 entry 值的基本組件擴展而來的,因為此應用程序中有許多相同類型的組件。
您可能在組件中使用了changeDetection: ChangeDetectionStrategy.OnPush在這種情況下嘗試手動觸發 changeDetection ChangeDetectorRef
constructor(
private _entryService: EntryService,
private changeDetectionRef: ChangeDetectorRef
) {}
ngOnInit(): void {
this._entryService.entry.subscribe(entry => {
this.entry = entry;
this.changeDetectionRef.detectChanges();
});
}
這是語法的問題。 中間漏掉了分號。 你應該寫
<span *ngIf="entry.customer; else no">
<h1>Hello</h1>
</span>
您也可以使用“then”或“then else”
<span *ngIf="entry.customer; then content">
<h1>Hello</h1>
</span>
問題原來是我已將組件添加到模塊中,但沒有將模塊添加到 app.module 中。 感謝@raj m 的回答讓我找到了解決方案。 https://stackoverflow.com/a/42066452/2793683
<span *ngIf="entry.customer; else no">
<h1>Hello</h1>
</span>
<ng-template #no>
<h1> NOPE</h1>
</ng-template>
; <span *ngIf="entry.customer; else no"> 您的代碼中缺少 [分號]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.