简体   繁体   中英

Angular - *ngIf not evaluating

I'm attempting to troubleshoot an issue and have written the following code to see what is going on, but now I am even further confused. Ideally if entry.customer has a value it should be printed and then Hello should also be displayed, otherwise NOPE and Goodbye should be displayed, but the actual result is that only the value of entry.customer is displayed.

<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>

When I started tracking down this issue I thought that maybe there was an issue with change detection due to the value of entry coming from a BehaviorSubject, so I attempted getting the values in a zone, but that didn't change the result.


ngOnInit(): void {
   this.ngZone.run(() => {
     debugger;
     this._entryService.entry.subscribe(entry => {
       debugger;
       this.entry = entry;
     });
   })
 }

Can anyone explain a possible reason why *ngIf won't work, yet using the curly braces does display the value? If it helps any the component that I am using is extended from a base component that gets the value of entry as there are many components of the same type in this application.

You may have used changeDetection: ChangeDetectionStrategy.OnPush in your component in that case try to trigger changeDetection manually ChangeDetectorRef

constructor(
    private _entryService: EntryService,
    private changeDetectionRef: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    this._entryService.entry.subscribe(entry => {
      this.entry = entry;
      this.changeDetectionRef.detectChanges();
    });
  }

This is the issue with syntax. Semicolon is missed in between. You should write

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

You can also use "then" or "then else"

<span *ngIf="entry.customer; then content">
  <h1>Hello</h1>
</span>

The issue turned out to be that I had added the component to the module, but hadn't added the module to the app.module. Thanks to @raj m for this answer that led me to the solution. https://stackoverflow.com/a/42066452/2793683


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

; [ semicolon] is missed in your code in <span *ngIf="entry.customer; else no">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM