Reputation: 383
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
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
.
Upvotes: 6
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
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