Setting class for all Angular templates renderable with *ngIf

Issue

I have a class section on a DIV to be rendered. It works as expected.

<div *ngIf="decoded; then coordinates"></div>
<ng-template #coordinates>
  <div class="section">...</div>
</ng-template>

I tried moving the class assignment to the DIV containing the directive. The rendition did not work, though.

<div *ngIf="decoded; then coordinates" class="section"></div>
<ng-template #coordinates>
  <div>...</div>
</ng-template>

The outer DIV vanishes as a whole, being replaced by the contents of the template. It bugs me because I’m forced to add an extra DIV around everything in my template if I have several components in it. (Also, it seems kind of weird to me that we don’t retain any properties of the tag used with *ngIf and can use any arbitrary one, while it seems to work for *ngFor.)

<div *ngIf="decoded; then coordinates"></div>
<ng-template #coordinates>
  <div class="section">
    <div>...</div>
    <span>...</span>
    <bzz>...</bzz>
  </div>
</ng-template>

I tried cheating the browser by setting the class on template but since it’s not actually rendered in the DOM as such, it failed, of course.

<div *ngIf="decoded; then coordinates"></div>
<ng-template #coordinates class="section">
  <div...</div>
</ng-template>

is there a way to force the DIV with the conditional directive to retain its class when being rendered according to the template’s contents?

Solution

You can try to use ng-container and apply *ngIf to it, in this case it should work as you expected

<div class="section">
  <ng-container *ngIf="decoded; then coordinates"></ng-container>
</div>

<ng-template #coordinates>
  <div>...</div>
</ng-template>

Answered By – Slawa Eremin

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.