Skip to content Skip to sidebar Skip to footer

Populating Angular Reactive Forms Correcctly

In an angular 7 app, I have created a list of managers. When a user clicks on an item, a view with a populated form should be displayed where the user can then update the manager d

Solution 1:

You will need to make the following changes when you initialise your editManagerForm. You should use a FormBuilder to generate your Form Group and Form Controls.

Do remember to import formBuilder and formGroup on your component.

import { FormBuilder, FormGroup } from'@angular/forms';
.
.
constructor(private formBuilder: FormBuilder,
) { }

editManagerForm: FormGroup = this.formBuilder.group({
    firstName: [null],
    lastName: [null],
    username: [null],
    password: [null],
    terminal: [null],
}

I assume you will populate the editManagerForm on the managerDetails() method. You can achieve this by using patchValue:

managerDetails() {
  const managerId = this.route.snapshot.paramMap.get("id");

  this.managerService.getManager(managerId).then(data => {
    this.editManagerForm.patchValue(data);
  });
}

Note: I am assuming that the data you fetched from getManager() is an object in the following format

data = {
  firstName: '',
  lastName: '',
  username: '',
  password: '',
  terminal: ''
}

Post a Comment for "Populating Angular Reactive Forms Correcctly"