0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.