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

Angular: ng-content doesn't render with *ngIf then else

I want to style the content differently depending on the [id] of the popup-content.
Now only the ‘then’ case of *ngIf renders when the conditions are true.
If the conditions aren’t met, the <ng-content> inside the else case doesn’t.
Is there something wrong with this code?

  1. The if else itself works if I remove the ng-content and replace it with plain text
  2. id == ‘login-popup’ connection works well too
.content {
  background-color: #03448f;
  opacity: 0.72;
}

.content-solid-bkgd {
  background-color: #03448f;
  opacity: 0.92;
}
<div *ngIf=" id == 'login-popup' || id == 'language-popup'; then lowOpacity; else highOpacity; "></div>

<ng-template #lowOpacity>
  <div [ngClass]="'content'">
    <ng-content select=".popup-content"></ng-content>
  </div>
</ng-template>
<ng-template #highOpacity>
  <div [ngClass]="'content-solid-bkgd'">
    <ng-content select=".popup-content"></ng-content>
  </div>
</ng-template>
</div>

If I type random text between <ng-template> and <div> of the "ELSE" case,
the text gets rendered but not the <ng-content>
ie:

 <ng-template #highOpacity>
      randomTestingText
        <div [ngClass]="'content-solid-bkgd'">
            <ng-content select=".popup-content"></ng-content>
        </div>
    </ng-template>

TIA

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 :

I don’t understand why you are using ng-content two times to render the same thing, all I can see is a change of class, just use a ternary operator with ngClass to toggle the classes!

.content {
  background-color: #03448f;
  opacity: 0.72;
}

.content-solid-bkgd {
  background-color: #03448f;
  opacity: 0.92;
}
<div [ngClass]="id == 'login-popup' || id == 'language-popup' ? 'content' : 'content-solid-bkgd'">

  <ng-content select=".popup-content"></ng-content>
</div>
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