2
votes

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.

2
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? - Thomas Cayne
@ThomasCayne I have made some changes does it clear the confusion now - Varun Sukheja
Aha! I understand now. I'll post my answer below - Thomas Cayne

2 Answers

3
votes

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.

1
votes

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.