I have an array of objects as:
arr = [{
"name": "firstName",
"type": "text",
"required": false
},
{
"name": "lastName",
"type": "text",
"required": false
},
{
"name": "dob",
"type": "date",
"required": false
}
]
I am creating a form in HTML using *ngFor and formControlName as follows:
createFormgroup() {
arr.forEach((control: any) => {
this.createFormGroup.addControl(
control.name,
this.fb.control(false)
);
this.createFormGroup.addControl(
"required" + i,
this.fb.control(false)
);
});
}
submit(form: NgForm) {
console.log(form.value)
}
<mat-label>Enter form name:</mat-label>
<input class="form-name-input" matInput placeholder="Form Name" formControlName="formName" required>
<form [formGroup]="createFormGroup" (ngSubmit)="submit(createFormGroup)">
<div *ngFor="let a of arr; let i = index">
<mat-checkbox formControlName="{{a.name}}">{{ a.name }}</mat-checkbox>
<mat-checkbox formControlName="required{{i}}">required</mat-checkbox>
</div>
<button type="submit">submit</button>
</form>
Here I am trying to achieve to show and post the values together as an object respective to the other. For example, if I check the First name, dob, and the required in HTML, I want the whole object when clicked on submit(). When clicked on submit(), I am looking for output like:
form.value = [{
"name": "firstname",
"type": "text",
required: true
}, {
"name": "dob",
"type": "date",
required: false
}]
I am confused about how to achieve this. Is there a way? Also, I need to assign different formControl names for each required field. I am not sure how to do that.
I am attaching an image for understanding. UI image
Note: I know how to get values from a form, but I am looking for a way to copy the whole object
To keep it simple: I need same array which I used to create form, and at the end I need same array with same object properties changed as per user input