Search code examples
javascriptarraysangularloopsproperty-binding

How to do nested loops inside template view in angular2+


I need to view different array indexes and their values inside my template. I have this object:

vegetables = [
    {name: 'Carrot', type: 'vegetable'},
    {name: 'Onion', type: 'vegetable'},
    {name: 'Potato', type: 'vegetable'},
    {name: 'Capsicum', type: 'vegetable'}],
    [
      {name: 'Carrotas', type: 'vegetable'},
      {name: 'Onionas', type: 'vegetable'},
      {name: 'Potatoas', type: 'vegetable'},
      {name: 'Capsicumas', type: 'vegetable'}]

And I do this:

 <li class="list-group-item list-group-item-action list-group-item-success" [draggable] *ngFor="let items of [vegetables[0]]"
                        [dragClass]="'active'" [dragTransitClass]="'active'" [dragData]="item" [dragScope]="item.type" [dragEnabled]="dragEnabled">
                        {{item.name}}
                    </li>

But [vegetables[0]] only outputs "Carrot" from the list and that's it. Instead I need it to output first array and all its content, then on the second iteration, output second array with "Carrotas", "Onionas" etc. How do achieve this?

0 will be replaced with i which will be incremented every time to go through different arrays of lists inside vegetables.


Solution

  • First of all, array you provided is wrong. I'm assuming it will be like this:

    vegetables = [[
    {name: 'Carrot', type: 'vegetable'},
    {name: 'Onion', type: 'vegetable'},
    {name: 'Potato', type: 'vegetable'},
    {name: 'Capsicum', type: 'vegetable'}],
    [
      {name: 'Carrotas', type: 'vegetable'},
      {name: 'Onionas', type: 'vegetable'},
      {name: 'Potatoas', type: 'vegetable'},
      {name: 'Capsicumas', type: 'vegetable'}]]
    

    If I understood correctly, either you'll have to write with *ngIf for indexes (e.g. check if index is odd or even), or reduce them to be a single one. e.g:

    const vegetablesReduced = vegetables.reduce((r, x) => [...r, ...x], []);
    

    This will create array like:

    vegetablesReduced = [
      {name: 'Carrot', type: 'vegetable'},
      ...
      {name: 'Carrotas', type: 'vegetable'},
      ...
    ];
    

    EDIT: Ah.. I only see that your problem lays in array definition only. The way you have array created there is false, since you're creating only first one and second is ignored (javascript...). Try to change array as I provided and see if it works.

    EDIT2: It should be 2D array, while you have only 1D (and also with mistake, since 1D arrays can't be split into multi arrays) What you're missing is only to wrap that whole thing into another array and it will work.