Jydon Mah
Jydon Mah

Reputation: 383

Angular 4 | creating extra div when *ngIf is triggered

Good day, i am doing right here? im calling an API data but when in my if condition it seems to create extra div when validating to false.

<div *ngFor="let apidata of data">
    <div class="box" *ngIf="apidata.Zone == 8">
      <div class="box-assignmentnumber-holder">
        <span id="AssignmentNumber">{{apidata.Assignment}}</span>
      </div>
      <div class="newAssignment">
        <span>{{ apidata.Operator == null ? 'New' : apidata.Operator }}</span>
      </div>
    </div>
  </div>

what would be the best approach here to eliminate the extra div in my code?

example result below..

<div></div> <---extra div when false
<div></div> <---extra div when false
<div class="box">
     <div class="box-assignmentnumber-holder">
          <span>123123</span>
     </div>
</div>
<div></div> <---extra div when false

Upvotes: 2

Views: 2617

Answers (3)

Vivek Doshi
Vivek Doshi

Reputation: 58553

All you need to do is replace div with ng-container of *ngFor :

<ng-container *ngFor="let apidata of data">
    <div class="box" *ngIf="apidata.Zone == 8">
        <div class="box-assignmentnumber-holder">
            <span id="AssignmentNumber">{{apidata.Assignment}}</span>
        </div>
        <div class="newAssignment">
            <span>{{ apidata.Operator == null ? 'New' : apidata.Operator }}</span>
        </div>
    </div>
<ng-container>

This will not create extra divs if condition is false.

WORKING DEMO

Upvotes: 6

J Sulivan
J Sulivan

Reputation: 50

Regardless of your condition is true or false you'll always have a div created because of the loop

<div *ngFor="let apidata of data">

Try This

<ng-container *ngFor="let apidata of data">
    <div class="box" *ngIf="apidata.Zone == 8">
        <div class="box-assignmentnumber-holder">
           <span id="AssignmentNumber">{{apidata.Assignment}}</span>
        </div>
        <div class="newAssignment">
           <span>{{ apidata.Operator == null ? 'New' : apidata.Operator }}
           </span>
        </div>
    </div>
 </ng-container>

Upvotes: 1

Rahul Singh
Rahul Singh

Reputation: 19622

Make use of ng-container instead of div

In order to avoid having to create that extra div, we can instead use ng-container directive:

ng-container *ngIf="lessons">
    <div class="lesson" *ngFor="let lesson of lessons">
        <div class="lesson-detail">
            {{lesson | json}}
        </div>
    </div>
</ng-container>

As we can see, the ng-container directive provides us with an element that we can attach a structural directive to a section of the page, without having to create an extra element just for that.

There is another major use case for the ng-container directive: it can also provide a placeholder for injecting a template dynamically into the page.

Reference - https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/

Upvotes: 1

Related Questions