Jon Sud
Jon Sud

Reputation: 11641

How to bind reactive angular form into object as two-way databind?

I have angular form:

profileForm = new FormGroup({
 firstName: new FormControl(''),
 lastName: new FormControl(''),
});

<form [formGroup]="profileForm">

  <label>
    First Name:
    <input type="text" formControlName="firstName">
  </label>

  <label>
    Last Name:
    <input type="text" formControlName="lastName">
  </label>

</form>

Also I have an data object:

const person = { firstName: 'firstbla', lastName: 'lastbla' }

I want to bind the object into the form.

But when I form.firstName change it also reflect the change in person.firstName. (two-way data binding).

Is it possible to do in angular reactive form ? I try with patchValue, but it doesn't change the person.

Upvotes: 0

Views: 946

Answers (2)

BhargavG
BhargavG

Reputation: 906

You can use ValueChanges. Form initialisation will be like this,

profileForm = new FormGroup({
 firstName: new FormControl(person && person.firstName ? person.firstName : ''),
 lastName: new FormControl(person && person.lastName ? person.lastName : ''),
});

You have to create one new method in the ngOnInit() after form initialisation method,

detectValueChange = () => {
this.profileForm.valueChanges.subscribe((response) => {
      person.firstName = response.firstName;
      person.lastName = response.lastName;
    })
};

This way both your form and object's value will be on the same page.

Upvotes: 1

Saloo
Saloo

Reputation: 816

patchValue update the values in the form.

Reactive form also works in two way binding. Whatever change you do in form , you can get the values. In this case,you can initialize the form with object values.

const person = { firstName: 'firstbla', lastName: 'lastbla' }

profileForm = new FormGroup({
 firstName: new FormControl(person.firstName),
 lastName: new FormControl(person.lastName),
});

Whenever you make any changes in the form, before submit you can call:

const formValues = profileForm.value;
const firstName = formValues.firstName;
const lastName = formValues.lastName;

Upvotes: 0

Related Questions