Search code examples
javascriptangulartypescriptobjectngmodel

Angular - ngModel object property from variable


I have the following user object in my application:

let user = {name: "John", dob:"1995-10-15", metadata: {}}

The metadata property of my object is an empty object. On user input, I want to create a new property in the metadata object such as:

<input [(ngModel)]="user.metadata.childrenNumber" placeholder="Enter number of children"></input>

So far so good, everything works as expected. However, the childrenNumber property I have stored in an array:

let metaDataOptions = ['childrenNumber', 'workStatus', 'education'];

How can I reference the property's name I wish to be created from that array? For the case above I tried to do something like this:

// i is index from ngFor. i can be 0, 1 or 2
<input [(ngModel)]="user.metadata.metaDataOptions[i]" placeholder="Enter number of children"></input>

However, this does not work. How can I achieve the result I desire?


Solution

  • Keep below object as it is.

    let user = {name: "John", dob:"1995-10-15", metadata: {}}
    let metaDataOptions = ['childrenNumber', 'workStatus', 'education']
    

    You can create object property inside the metadata object using below line of code.

    <input [(ngModel)]="user.metadata[metaDataOptions[i]]" placeholder="Enter number of children"></input>