简体   繁体   中英

Editing object with Angular reactive forms

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)?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM