0

I am trying to access from an html through a variable to the property of an object that has several levels something similar to the following:

Variable named rows

[
  {
    name: "Row1",
    levels: {
             name:"name1",
             things: {
                     name: "thing1"
                     }
            }
  },
  {
    name: "Row2",
    levels: {
             name:"name2",
             things: {
                     name: "thing2"
                     }
             }
   }

]

Variable named columns

[
    {
       id:"col1",
       properties:"name"
    },
    {
       id:"col2",
       properties:"levels.name"
    },
    {
       id:"col1",
       properties:"levels.thing.name"
    }
]

HTML

<div *ngFor="let row of rows ">
      <div *ngFor="let col of columns">
           {{ row[col.properties] }}
      </div>
</div>

HTML result

Row1
undefined
undefined
Row2
undefined
undefined

The problem is that there will not always be the same number of sublevels since it is for a common component, the levels and the organization are passed by the "Columns" variable.

In the previous code the values of the first level are shown, but the The rest is not, it shows them as undefined since it does not access the internal object.

1 Answers1

0

What about this:

<div *ngFor="let row of rows ">
      <div *ngFor="let col of columns">
           {{ col.properties.split('.').reduce((acc, prop) => acc[prop], row) }}
      </div>
</div>

Edit:

Bindings cannot contain assignments.

<div *ngFor="let row of rows ">
      <div *ngFor="let col of columns">
           {{ deepGet(col.properties, row) }}
      </div>
</div>
// ...
  deepGet(path: string, obj: any): string {
    return path.split('.').reduce((acc, prop) => acc[prop], obj);
  }
// ...
zouabi
  • 649
  • 1
  • 7
  • 16
  • Hello, thank you very much for the answer but when I add that in the code it stops compiling since the error appears Parser Error: Missing expected ) en este ejemplo pasa lo mismo https://stackblitz.com/edit/angular-2yjfwz?file=src%2Fapp%2Fapp.component.ts – user22415411 Aug 22 '23 at 11:25
  • In javascript if I add it in a function if it compiles and behaves properly – user22415411 Aug 22 '23 at 11:42
  • @user22415411 please refer to: https://stackoverflow.com/a/43118484/11019230. You have to move it to the component class. – zouabi Aug 23 '23 at 03:27