How to edit and update reactive form in Angular?
author
,
Aspirant Programmer

Please give a step by step guidance to edit and update form element values in Angular?

  • Total 1 Answer
  • 420
Can You answer this question?
author
,
Aspirant Programmer

If you have a list of records and now you want a edit screen to edit and update the record then you can do it using following steps:

1- Import forms module in component

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

2- Then declare variables of form builder and form group

public testform: FormGroup;

  constructor(

    public share: ShareService,

    public fb: FormBuilder

  ) { }

3- Create a form 

ngOnInit(){

    this.testform = this.fb.group({

      id: [''],

      first_name: [''],

      last_name: [''],

      phone: ['']

    });

  }

4- Then on click of edit set form element values using patchValue and display it

showForm(data){

    this.formData = data;

    this.testform.patchValue({

      id:data.id,

      first_name:data.first_name,

      last_name:data.last_name,

      phone:data.phone

    });

  }

5- On component html show data as below 

<form name="test-form" *ngIf="formData" [formGroup]="testform" (ngSubmit)="updateUser(testform)"><br /> <input type="hidden" name="id"  formControlName="id" value="{{formData.id}}" /><br /> <input type="text" name="first_name" formControlName="first_name" placeholder="Enter a First Name" value="{{testform.value.first_name}}" /><br /> <input type="text" name="last_name" formControlName="last_name" placeholder="Enter a Last Name" value="{{formData.last_name}}" /><br /> <input type="text" name="phone" formControlName="phone" placeholder="Enter a Phone" value="{{formData.phone}}" /><br /> <input type="submit" name="submit" value="Submit" /><br /> </form>

These are a very simple and easy steps to edit and display form data and when you submit, it will be accessible as below

updateUser(testform){

    let userData:any = {};

    userData.id = testform.value.id;

    userData.first_name = testform.value.first_name; 

    userData.last_name = testform.value.last_name; 

    userData.phone = testform.value.phone; 

    this.share.updateUserData(userData).subscribe((res)=>{

      console.log(res);

    });

  }

Here this.share.updateUserData is a service to update record which communicate with nodejs through API.