SA-
SA-

Reputation: 151

Html, Place items from an array in the top/bottom <div> based on a property

I am trying to place items 'next to each other' in either the top or bottom section depending on a property called 'section':

<span *ngFor="let item in [{name:"name1",section:"bottom"},{name:"name2",section:"top"}, 
{name:"name3",section:"top"},{name:"name4",section:"bottom"},{name:"name5",section:"bottom"}]">
    <span *ngIf="item.section=='top'">{{ item.name }}<span>
</span>

The result should look like this:
<div> name2 name3 </div>
<div> name1 name4 name5 </div>

Any help please? I can't seem to figure it on my own, thanks.

Upvotes: 0

Views: 139

Answers (1)

Hadi Golkarian
Hadi Golkarian

Reputation: 36

you can use two *ngFor each including an *ngIf for every section(top/bottom) like this: (considering you have your data in array property called foo)

<div>
    <ng-container *ngFor="let item of foo">
        <span *ngIf="item.section=='top'">
          {{ item.name }}
        </span>
    </ng-container>
</div>
<div>
    <ng-container *ngFor="let item of foo">
        <span *ngIf="item.section=='bottom'">
          {{ item.name }}
        </span>
    </ng-container>
</div>

if you have more than just two valid values for section property you can use this code to have more dynamic template according to your section values: (considering you have your section values in array property called bar)

<ng-container *ngFor="let section of bar">
    <div>
        <ng-container *ngFor="let item of foo">
            <span *ngIf="item.section==section">
              {{ item.name }}
            </span>
        </ng-container>
    </div>
</ng-container>

working example: stackblitz example

Upvotes: 1

Related Questions