0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;

2 Comments

I want the person.firstname to be bind as two-way databind in reactive form. without ngmodel, which doesn't happends in your example
Reactive form hides this ngModel and do two way binding using formControlName what you have used in form fields.

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.