dmoore1181
dmoore1181

Reputation: 2102

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.

Upvotes: 0

Views: 1402

Answers (4)

Gem
Gem

Reputation: 545


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

Upvotes: 0

dmoore1181
dmoore1181

Reputation: 2102

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

Upvotes: 0

Aarti Bhardwaj
Aarti Bhardwaj

Reputation: 21

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>

Upvotes: 0

Gobika
Gobika

Reputation: 324

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();
    });
  }

Upvotes: 2

Related Questions