[英]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.