简体   繁体   中英

Angular Reactive Form clone value

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.

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM