Home > other >  How to update the nested object in Angular reactive form
How to update the nested object in Angular reactive form

Time:08-27

I am working with Angular 14 framework and looking for a very simple approach. Suppose I want to add a client with the additional contact details. My Angular reactive form is,

form = this.fb.group({
  client_Id: [0],
  client_Name: [''],
  client_Contacts: this.fb.array([])
})

Now my API is also emitting a JSON like,

{"client_Id":"1","client_Name":"Nikhil","client_Contact":[{"place":"Home","number":"1111111"}, {"place":"Work","number":"2222222"}]}

Now creating a new client entry with reactive form is simple. But updating data is quite a pain.

Is there a best solution for the updating?

CodePudding user response:

You can use the below sample code, basically use patchValue the top level values, then do a for loop of the array and push the formGroups into the formArray!

ts

import { Component } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  FormArray,
  FormControl,
  Validators,
} from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  orderForm: FormGroup;
  items: FormArray;

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.orderForm = this.formBuilder.group({
      client_Id: '',
      client_Name: '',
      client_Contacts: this.formBuilder.array([]),
    });
    const apiResponse = {
      client_Id: '1',
      client_Name: 'Nikhil',
      client_Contact: [
        { place: 'Home', number: '1111111' },
        { place: 'Work', number: '2222222' },
      ],
    };
    this.orderForm.patchValue(apiResponse);
    apiResponse.client_Contact.forEach((x) => {
      this.orderForm.controls.client_Contacts.push(
        this.formBuilder.group({
          place: x.place,
          number: x.number,
        })
      );
    });
  }

  createItem(): FormGroup {
    return this.formBuilder.group({
      name: '',
      description: '',
      price: '',
    });
  }

  addItem(): void {
    this.items = this.orderForm.get('items') as FormArray;
    this.items.push(this.createItem());
  }
}

html

<hello name="{{ name }}"></hello>
<p>Start editing to see some magic happen :)</p>
<form [formGroup]="orderForm">
  <input formControlName="client_Id" placeholder="Item name" />
  <input formControlName="client_Name" placeholder="Item name" />
  <div
    formArrayName="client_Contacts"
    *ngFor="
      let item of orderForm.get('client_Contacts').controls;
      let i = index
    "
  >
    <div [formGroupName]="i">
      <input formControlName="place" placeholder="Item name" />
      <input formControlName="number" placeholder="Item description" />
    </div>
  </div>
</form>
<button (click)="addItem()">Add</button>

stackblitz

  • Related