Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading