angularng-template

ngIf displays template on else condition and nothing when condition is true


I want to diplay different texts depending whether the variable this.showThis is true or false and I wrote the following code in angular to achieve this:

<mat-checkbox class="med-checkbox" (change)="onChange($event)" [checked]="protocol.showInProtocol">
  <ng-template *ngIf="this.showThis; else elseContent">
    String goes here
  </ng-template>
  <ng-template #elseContent>
    Else goes here
  </ng-template>
</mat-checkbox>

The text "Else goes here" is correctly displayed when this.showThis === false. However, the text "String goes here" is not shown when this.showThis === true.

I'm expecting to shpw different texts based on whether the condition is true or false, and I'm using two different ng-template tags to achieve this.


Solution

  • Your *ngIf is translated to template attribute by angular

    Check the docs https://angular.io/guide/structural-directives

    If you want to use ng-template with ngIf to switch the texts try the following code

    <ng-template [ngIf]="showThis" [ngIfElse]="elseContent">
        String goes here
    </ng-template>
    <ng-template #elseContent>
        Else goes here
    </ng-template>