Search code examples
javascriptangularangular-ng-if

*ngIf does not toggle back to false in else block


I am using Angular7, npm 6.4.1, node 10.15.3.

I am just playing around with ngIf, this does nothing useful. I am using two buttons to toggle back and forth between displaying and hiding a header. While it was just an ngIf statement, it was working fine with the following code:

    <p>Do you want to see the last header?</p>
    <button (click)="yesHeader()">Yes please!</button>
    <button (click)="noHeader()">PLEASE G-D NO!</button>

    <h2 *ngIf="displayHeader" style="color:blue">Here it is in all its glory!</h2>

and

public displayHeader=false;

  yesHeader(){
    this.displayHeader=true
  }

  noHeader(){
    this.displayHeader=false
  }

And that worked fine, showing the header when clicking the yesHeader button and hiding it again when clicking the noHeader button.

However, when I added an ngIf Else block, it stopped toggling back and forth. The change was to the following:

    <p>Do you want to see the last header?</p>
    <button (click)="yesHeader()">Yes please!</button><button (click)="noHeader()">NO! NO!</button>

    <h2 *ngIf="displayHeader; else noHeader" style="color:blue">Here it is in all its glory!</h2>

    <ng-template #noHeader>
      <h5>You don't know what you're missing!</h5>
    </ng-template>

Now, it displays You don't know what you're missing! at start, and switches to the header if I click yes. But it doesn't toggle back to hiding the header if I click the no button after that.

What am I doing wrong and how can I get it to toggle back?

As an added datapoint, if I leave the else block, but take else noHeader out of the ngIf statement, it still doesn't toggle back. So seemingly the existence of the ng-template is what is stopping things up.


Solution

  • The issue is that there is a name conflict of noHeader. It being used in your example as both a method on the component class as well as the name of the ng-template. Try changing either the name of the method or name of the template:

    <p>Do you want to see the last header?</p>
    <button (click)="yesHeader()">Yes please!</button><button (click)="noHeader()">NO! NO!</button>
    
    <h2 *ngIf="displayHeader; else noHeaderTemplate" style="color:blue">Here it is in all its glory!</h2>
    
    <ng-template #noHeaderTemplate>
      <h5>You don't know what you're missing!</h5>
    </ng-template>
    

    Here is an example in action.