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.

3
  • Where will the name and username be stored? also it depends on your use case. Are you referring to this.form.valueChanges? or a template variable? or a autocomplete field? Can you specify what you have written so far? Commented Aug 20, 2019 at 19:27
  • @ThomasCayne I have made some changes does it clear the confusion now Commented Aug 20, 2019 at 19:35
  • Aha! I understand now. I'll post my answer below Commented Aug 20, 2019 at 19:50

2 Answers 2

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.

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

4 Comments

I was going to suggest this way, also. However, always remember to unsubscribe() or else we'll experience memory hog. Refer to: stackoverflow.com/a/54205373/4208845
@ThomasCayne Yes, unsubscribe is needed to avoid memory leaks. I updated my answer.
@ThomasCayne why this answer is better than using a reference ?
#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.
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.