Search code examples
angularngforangular-flex-layout

Angular *ngFor on different divs


I have a markup using material flex in angular 4 project which looks like this.

<div fxLayout="row">
  <div fxFlex="65">
    
  </div>
  <div fxFlex="35">
    
  </div>
</div>

enter image description here

And I have an array of elements like this:

public array: [object] = [
    {
        firstName: 'value',
        lastName: 'value'
    },
    {
        firstName: 'value',
        lastName: 'value'
    },
    {
        firstName: 'value',
        lastName: 'value'
    },
    {
        firstName: 'value',
        lastName: 'value'
    },
    {
        firstName: 'value',
        lastName: 'value'
    },
];

I want to loop through this array and fill half of all elements in 65% div and the rest of elements in 35% div. How to do it with *ngFor directive correctly? Now I have solution like this. But it looks horrible and not readable.

    <div fxLayout="row">
      <div fxFlex="65">
        <div *ngFor="let item of array; let i = index">
          <div *ngIf="i < 3">
            <p>{{ item.firstName }}</p>
            <p>{{ item.lastName }}</p>
          </div>
        </div>
      </div>
      <div fxFlex="35">
        <div *ngFor="let item of array; let i = index">
          <div *ngIf="i >= 3">
            <p>{{ item.firstName }}</p>
            <p>{{ item.lastName }}</p>
          </div>
        </div>
      </div>
    </div>

Is there any other solutions to do that? I also tried using <template> element. But my tries failed. Please help me with that!


Solution

  • You can use the SlicePipe, as shown in this plunker.

    <div fxLayout="row">
        <div fxFlex="65">
            <div *ngFor="let item of array | slice:0:half">
                <p>{{ item.firstName }}</p>
                <p>{{ item.lastName }}</p>
            </div>
        </div>
        <div fxFlex="35">
            <div *ngFor="let item of array | slice:half">
                <p>{{ item.firstName }}</p>
                <p>{{ item.lastName }}</p>
            </div>
        </div>
    </div>
    

    The half property would be defined in the component class:

    import {Component} from '@angular/core';
    
    @Component({
      ...
    })
    export class Component1 {
        public array: [object] = [
            {
                firstName: 'first1',
                lastName: 'last1'
            },
            {
                firstName: 'first2',
                lastName: 'last2'
            },
            ...
        ];
        public get half(): number {
            return Math.ceil(this.array.length / 2);
        }
    }