1

How do I edit an object with reactive forms? Lets' assume we have an array of objects :

people = [
{name: "Janek", color:"blue", id: 1},
{name: "Maciek", color:"red", id: 2},
{name: "Ala", color:"blue", id: 3},
]

If I want to edit object's properties with Template Driven approach - it's farily easy. HTML

*ngFor="let person of people" 

and

ngModel="person.name" plus "person.color"

How to do this with Reactive Forms, so that I don't loose Id (and other properties)?

1 Answer 1

5

Give this a try:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  people = [
    { name: "Janek", color: "blue", id: 1 },
    { name: "Maciek", color: "red", id: 2 },
    { name: "Ala", color: "blue", id: 3 },
  ];
  peopleForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.peopleForm = this.fb.group({
      people: this.fb.array(this.people.map(person => this.fb.group({
        name: this.fb.control(person.name),
        color: this.fb.control(person.color),
        id: this.fb.control(person.id)
      })))
    });
  }

  get peopleArray() {
    return (<FormArray>this.peopleForm.get('people'));
  }

  onSubmit() {
    console.log(this.peopleForm.value);
  }

}

And in your Template:

<form [formGroup]="peopleForm">
  <div formArrayName="people">
    <div *ngFor="let person of peopleArray.controls; let i = index;">
      <div [formGroupName]="i">
        <input type="text" formControlName="name">
        <input type="text" formControlName="color">
        <input type="text" formControlName="id">
      </div>
    </div>
  </div>
  <button type="submit" (click)="onSubmit()">Submit</button>
</form>

Here's a Working Sample StackBlitz for your ref.

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.