2

I am using Angular Reactive Form for the signup form.

 this.personalDataForm = new FormGroup({
      'name': new FormControl(null, Validators.required),
      'username': new FormControl(null, Validators.required),
      'address': new FormControl(null, Validators.required),
      'email': new FormControl(null, [Validators.required, Validators.email]),
      'mobile': new FormControl(null),
      'password': new FormControl(null),
    });

In this form I want it to be as when user types in the name field similar value get auto-filled to username field

But when a user types into the username field, the name field is unaffected.

Please let me know how to achieve this using Reactive Forms.

Varun Sukheja
  • 6,170
  • 5
  • 51
  • 93

2 Answers2

3

To keep all your form manipulation logic in one place (in your TS file) which is the recommended way once you work with Reactive Forms.

Try this:

this.personalDataForm.get('name').valueChanges.subscribe((x) => {
  console.log('value has changed: ', x);
  this.personalDataForm.patchValue({ username: x });
});

To unsubscribe from the valueChanges check this answer: https://stackoverflow.com/a/46893278/2050306

Working stackblitz.

robert
  • 5,742
  • 7
  • 28
  • 37
  • I was going to suggest this way, also. However, always remember to `unsubscribe()` or else we'll experience memory hog. Refer to: https://stackoverflow.com/a/54205373/4208845 – Thomas Cayne Aug 20 '19 at 20:04
  • 1
    @ThomasCayne Yes, unsubscribe is needed to avoid memory leaks. I updated my answer. – robert Aug 20 '19 at 20:20
  • @ThomasCayne why this answer is better than using a reference ? – Varun Sukheja Aug 21 '19 at 19:11
  • `#nameTemplate` is a reference variable, as I answered below, and is the `simplest way` in this scenario when only `ONE` action is needed. Some people prefer the simple way. I used a mixture, and with custom directives when feasible, depending on the use cases. However, `form.valueChanges` can be used to do a combination of actions. For example, autocomplete, searching/sort, filtering, where a service will have to be called, to update a store, form, @Output(), etc. – Thomas Cayne Aug 21 '19 at 19:27
1

You can use a template variable on username like so (simplest way):

<input type="text" formControlName="name" #nameTemplate />

<input type="text" formControlName="username" [value]="nameTemplate.value"/>

Whatever you type in name field will reflect in the username field but not vice-versa. and the form will hold the value of username.

Thomas Cayne
  • 1,132
  • 8
  • 15