1

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.

André
  • 1,602
  • 2
  • 12
  • 26
  • Could this help? https://stackoverflow.com/questions/44837756/why-ngif-doesntwork-with-ng-template – manjiro sano Mar 17 '23 at 10:40
  • Thank you, I marked as duplicate. I'm not going to delete though cause I didn't find this before and SO didn't pointed me out before I posted. – André Jul 25 '23 at 13:03

1 Answers1

3

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>