0

我正在尝试解决问题并编写以下代码以查看发生了什么,但现在我更加困惑。理想情况下如果entry.customer有值应该打印然后Hello也应该显示,否则应该显示NOPEand 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 值的基本组件扩展而来的,因为此应用程序中有许多相同类型的组件。

4

4 回答 4

1

在这种情况下,您可能在组件中使用了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();
    });
  }
于 2021-06-10T16:49:40.820 回答
0

问题原来是我已将组件添加到模块中,但没有将模块添加到 app.module 中。感谢@raj m 的回答让我找到了解决方案。https://stackoverflow.com/a/42066452/2793683

于 2021-06-10T17:32:46.403 回答
0

这是语法的问题。中间漏掉了分号。你应该写

<span *ngIf="entry.customer; else no">
  <h1>Hello</h1>
</span>

您也可以使用“then”或“then else”

<span *ngIf="entry.customer; then content">
  <h1>Hello</h1>
</span>
于 2021-06-10T16:53:57.277 回答
0

<span *ngIf="entry.customer; else no">
  <h1>Hello</h1>
</span>
<ng-template #no>
  <h1> NOPE</h1>
</ng-template>

; <span *ngIf="en​​try.customer; else no"> 您的代码中缺少 [分号]

于 2021-06-11T03:37:36.340 回答