reactive from formGroupName values could not patch in edit form in Angular

49 Views Asked by At

Here is my code; get, post and delete is working fine and I am trying to patch value in edit form with routelink. I am getting data in the console but not getting value in edit form. If I remove formGroupName in html page it works but I need data with formGroup name and I am not getting data which is inside customerdetail group. The rest of it is working fine.

<div class="customerWrap">
     <form [formGroup] = 'customerForm' (ngSubmit)='customerUpdate()'>
        <div formGroupName = "customerDetail">
        <mat-form-field appearance = "outline">
            <mat-label>First Name</mat-label>
            <input matInput type="text"  formControlName = 'firstname'>
        </mat-form-field>

        <mat-form-field appearance = "outline">
            <mat-label>Last Name</mat-label>
            <input type="text" matInput formControlName ='lastname'>
        </mat-form-field>

        <mat-form-field appearance = "outline">
            <mat-label>Email</mat-label>
            <input type="text" matInput formControlName = 'email'>
        </mat-form-field>

        <mat-form-field appearance ="outline">
            <mat-label>Phone No</mat-label>
            <input type="text" matInput formControlName = 'phone'>
        </mat-form-field>
       </div>
        <mat-form-field appearance = "outline">
            <mat-label>Street</mat-label>
            <input type="text" matInput formControlName = 'street'>
        </mat-form-field>

        <mat-form-field appearance = "outline">`
            <mat-label>City</mat-label>
            <input type="text" matInput formControlName = 'city'>
        </mat-form-field>

        <mat-form-field appearance = "outline">
            <mat-label>State</mat-label>
            <input type="text" matInput formControlName = 'state'>
        </mat-form-field><br>

        <button mat-raised-button color="accent" type="submit">Update</button>
       </form>
      </div>

      </code></pre>

     <pre><code>
    import { Component, OnInit } from '@angular/core';
    import { NewCustomerService } from '../services/new-customer.service';
    import { JsonApiService } from '../services/json-api.service';
    import { MatDialog } from '@angular/material/dialog';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    import { ActivatedRoute, Router } from '@angular/router';

    @Component({
      selector: 'app-edit-product',
      templateUrl: './edit-product.component.html',
      styleUrls: ['./edit-product.component.scss']
    })
    export class EditProductComponent implements OnInit {

      constructor(
        private _jsonApiService:JsonApiService,
        public _dialog: MatDialog, 
        public _fb: FormBuilder,
        private _newCustomerService:NewCustomerService,
        private _router: ActivatedRoute,
        ){}
  
   
  
    customerForm!: FormGroup;
    
    customerFormData(){
      this.customerForm = this._fb.group({
        customerDetail: this._fb.group({
        firstname:[''],
        lastname:[''],
        email: [''],
        phone:[''],
        }),
        street:[''],
        city:[''],
        state:[''],
      })
    }
  customerUpdate(){
  
  }

  ngOnInit(): void {
    this. customerFormData()
    console.log(this._router.snapshot.params['id']);
    this._newCustomerService.getCustomerById(this._router.snapshot.params['id'])
    .subscribe({
      next:(res:any)=>{
        console.log(res)
        this.customerForm.patchValue({
          customerDetail: this._fb.group({
          firstname:res['firstname'],
          lastname:res['lastname'],
          email: res['email'],
          phone:res['phone'],
          }),
          street:res['street'],
          city:res['city'],
          state:res['state'],
        })
      }
    })
  }

 }



service#
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class NewCustomerService {

  constructor(
    private _http:HttpClient,
    ) { }
 newCustomerUrl:string = "http://localhost:3000/newCustomer"
    postNewCustomer(data:any){
      return this._http.post<any>(this.newCustomerUrl, data)
      .pipe(
        catchError(this.handleError)
      )
    }
  handleError(handleError: any): any {
    throw new Error("Method not implemented.");
  }

  getCustomer(){
    return this._http.get(this.newCustomerUrl)
  }

  deleteCustomer(id:number){
    return this._http.delete(`${this.newCustomerUrl}/${id}`)
  }
   getCustomerById(id:number){
     return this._http.get(`${this.newCustomerUrl}/${id}`)
   }
}
</code></pre>

<pre><code>
API#
[
  {
    "customerDetail": {
      "firstname": "ss",
      "lastname": "ss",
      "email": "ss",
      "phone": "ss"
    },
    "street": "ss",
    "city": "ssss",
    "state": "sss",
    "id": 7
  },
  {
    "customerDetail": {
      "firstname": "1",
      "lastname": "1",
      "email": "1",
      "phone": "1"
    },
    "street": "1",
    "city": "1",
    "state": "1",
    "id": 8
  },
  {
    "customerDetail": {
      "firstname": "2",
      "lastname": "2",
      "email": "2",
      "phone": "2"
    },
    "street": "2",
    "city": "2",
    "state": "2",
    "id": 9
  }
]
1

There are 1 best solutions below

1
Yong Shun On

When you patch value to the customerForm FormGroup, you don't need to create the FormGroup for customerDetails.

this.customerForm.patchValue({
  customerDetail: {
    firstname: res['customerDetail']['firstname'],
    lastname: res['customerDetail']['lastname'],
    email: res['customerDetail']['email'],
    phone: res['customerDetail']['phone'],
  },
  street: res['street'],
  city: res['city'],
  state: res['state'],
});

Or since the properties' names are the same as the FormControl names, you can patch the res object value to customerForm FormGroup.

this.customerForm.patchValue(res);

Demo @ StackBlitz