The Rock
The Rock

Reputation: 363

How to update dynamically generated keys and values in angular form

I have a data something like:

"data": [
   {
    "name": "Joe"
   },
   {
    "location": "USA"
   },
   {
    "age": "unknown"
   }
 ] 

NOTE: this object could be vary (not the fixed length).

I am displaying in the form like:

name(as a label): Joe (as an input value)

location(as a label): USA (as an input value)

age(as a label): unknown (as an input value)

app.component.html:

<form [formGroup]="angularForm">
   <div class="key-value-container" *ngFor="let item of values">
      <div class="key-value">
         <div class="key-value-lable">
            <label class="label">{{item.key}}</label>
         </div>
         <div class="input-container">
           <input class="input-text" matInput value="{{item.value}}">
         </div>
        </div>
      </div>
 <button type="button" class="primary-button" mat-flat-button (click)="_updateForm()">Update</button>
</form>

I want to UPDATE the data by POST method when I click on "_updateForm()" like:

{
 "key1" (name):"value1"(updated_name),
 "key2" (location):"value2"(updated_location),
 "key3"(age):"value3" (updated_age)
}

and how can I create formControlerName for this form?

Upvotes: 0

Views: 1217

Answers (1)

randombits.dev
randombits.dev

Reputation: 1376

formControlName can be set dynamically:

<input *ngFor="let field of dynamicData" [formControlName]="field.name">

The logic would be much easier if you changed your data to be something with consistent keys like:

 [
   {"label": "first", "value": "Mark"},
   {"label": "last", "value": "Smith"},
   {"label": "age", "value": "35"}
];

You can still accomplish with your data, just need some extra steps. See the following example that is similar to what you are trying to do:

https://stackblitz.com/edit/angular-form-array-dynamic?embed=1&file=src/app/app.ts

Upvotes: 1

Related Questions