Home > Back-end >  Angular: ng-content doesn't render with *ngIf then else
Angular: ng-content doesn't render with *ngIf then else

Time:08-24

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

CodePudding user response:

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>

  • Related