0

Hi I am using reactive form and I have section there where I want to populate values into another field

now for some reason when I use saved values from the browser it does not fill the email completely. it only takes first letter of the email and this happens sometimes when I fill the email form manually.

here is the live example of my code.

https://stackblitz.com/edit/angular-5l9kb4

Muhammad Ali
  • 369
  • 7
  • 23

1 Answers1

2

Updated

fillForm() {
  this.myForm.valueChanges.subscribe(value => {
    //I'm using .controls and .get, but both work here. Pick the one you prefer
    this.myForm.controls['second_phone'].setValue(value.phone, { emitEvent: false});
    this.myForm.get('second_email').setValue(value.email, { emitEvent: false});
  });
}

You can also use { onlySelf: true } in the setValue if needed (Ref: Angular 2 - FormControl setValue 'onlySelf' parameter)

and remove: value="{{myForm.get('email').value}}" from your secondary fields in your templates.


Not the best approach

Try this:

fillForm() {
    this.myForm.valueChanges.subscribe(value => {
      if ((!value.second_email && value.email) || (!value.second_phone && value.phone)) {
          value.second_phone = value.phone;
          value.second_email = value.email;
      } 
    });
  }
Community
  • 1
  • 1
Jojofoulk
  • 2,127
  • 1
  • 7
  • 25
  • 1
    Aight, I actually took advantage of the fact that you used `value="{{myForm.get('email').value}}"` in your template for your secondary field. Because I never actually set the value of your secondary fields, it works with your if statement. But now that I think of it, I realized it's pretty messy and bad practice. I updated the solution with a better approach that more logical – Jojofoulk Jun 18 '19 at 06:22
  • thanks it works now! but do you have another recommendation I am trying to come up with best practice – Muhammad Ali Jun 18 '19 at 06:25
  • perfect! wish I could vote your answer multiple times – Muhammad Ali Jun 18 '19 at 06:30
  • I'm glad it helped :) – Jojofoulk Jun 18 '19 at 06:30