0

I am trying to generate a table based on a JSON configuration. Although I can create the table headers OK, I don't know how to dynamically select the row cell data by field name. This is what I have:

columns = [
{
    heading: "Person's Name",
    fieldName = "name"
},
{
    heading: "Person's Age"
    fieldName = "age"
} ];

people = [ 
{
    name: "john",
    age: 25,
    gender: "male"
},
{
    name: "mary",
    age: 18,
    gender: "female"
} ];


<table> 

    <tr>
        <th *ngFor="let column of columns">{{column.heading}}</th>
    </tr>

    <tr *ngFor="let person of people">
        <td *ngFor="let column of columns">{{person.column.fieldName}}</td>
    </tr>

</table> 

Clearly {{person.column.fieldName}} does not work i.e. this does not translate into person.name and person.age.

Any thoughts on how to select the person field with the name of the fieldName specified in columns data?

2
  • well I don't know how this is even supposed to work. You have 2 completely independent ngFor's. There are now two options. Either ensure in your controller they are always in the correct order, or add another ngFor with the columns inside each person ngFor Commented Mar 9, 2018 at 14:12
  • Sorry my mistake - I've updated the code example now. So the problem I have is how to use the column.fieldName to select the right field from person. Commented Mar 9, 2018 at 14:17

1 Answer 1

2

You can access object properties by string indexer

obj.name or obj["name"]

<table> 

    <tr>
        <th *ngFor="let column of columns">{{column.heading}}</th>
    </tr>

    <tr *ngFor="let person of people">
        <td *ngFor="let column of columns">{{person[column.fieldName]}}</td>
    </tr>

</table> 
Sign up to request clarification or add additional context in comments.

3 Comments

Works a treat thank you! I should have know this doh!
even though not performant this should be the accepted answer. The other accepted answer does not even work. I highly recommend not using this approach since you just do a ton of unneeded ngFor loops.
I'm not sure why you say "unneeded ngFor loops" as they are needed? - or is there a better alternative?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.