Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 template: how to wrap contents of ngFor with DIV

I have uncertain count of columns and undefined length of fields. To display them there is this code:

<div class="col-md-6" *ngFor="let d of fields">
    <div class="form-group">
        <label>{{ d.displayName }}</label>
        <span>{{ viewRecord[d.fieldName]}}</span>
    </div>
</div

The result is :

<div class="col-md-6">
    <div class="form-group">
        <label>Title 1</label>
        <span>Text 1....</span>
    </div>
</div
<div class="col-md-6">
    <div class="form-group">
        <label>Title 2</label>
        <span>Text 2....</span>
    </div>
</div

Is there any possibility to put these two into one container like this:

<div class="row">
   <div class="col-md-6">
        <div class="form-group">
            <label>Title 1</label>
            <span>Text 1....</span>
        </div>
    </div
    <div class="col-md-6">
        <div class="form-group">
            <label>Title 2</label>
            <span>Text 2....</span>
        </div>
    </div
</div>

Please notice that I don't know count of fields, so I have to make modulus of 2 from total count of fields to wrap pair of fields into one container. It's obvious that wrapper will be outside of the cycle. I'm stuck :)

Note that I'm looking for template-driven answer. If there's not any, I can cope with it. Any JavaScript I can write myself ;)

like image 766
Roberc Avatar asked Jan 11 '17 11:01

Roberc


1 Answers

You can use built-in functionality of *ngFor, odd and even items. Iterate items as usual, but show result only when iterating even item. And using index to access item directly from items.

<div class="row">
    <div *ngFor="let d of fields; let index=index; let odd=odd; let even=even;">
        <div *ngIf="even">
            <div class="form-group" class="col-md-6">
                <label>{{ fields[index].displayName }}</label>
                <span>{{ viewRecord[fields[index].fieldName]}}</span>
            </div>
            <div class="form-group" class="col-md-6">
                <label>{{ fields[index+1].displayName }}</label>
                <span>{{ viewRecord[fields[index+1].fieldName]}}</span>
            </div>
        </div>
    </div>
</div>

It's definitely not the best solution (since I am defining the same template twice), but should work.

like image 108
Petr Adam Avatar answered Oct 13 '22 11:10

Petr Adam