0

I am using nested form group in angular6 app.

 export class NestedFormComponent implements OnInit {

  myForm: FormGroup

  constructor(private fb: FormBuilder) { 
    const phone = this.fb.group({
      area: [],
      prefix: [],
      line: []
    });

    this.myForm = this.fb.group({
      email: '',
      homePhone: phone,
      cellPhone: phone
    });

    this.myForm.valueChanges.subscribe(console.log)
  }

  ngOnInit() {
  }

}

<div id="formContainer">

<div>{{myForm.value | json}}</div>
<hr />

<mat-form-field class="example-full-width">
  <input matInput placeholder="email" formControlName='email'>
</mat-form-field>

<h4>Cell Phone</h4>
<div formGroupName='cellPhone'>

  <mat-form-field>
    <input type="text" plcaeholder='area' matInput formControlName='area'>
  </mat-form-field>

  <mat-form-field>
    <input type="text" placeholder="prefix" matInput formControlName='prefix'>
  </mat-form-field>

  <mat-form-field>
    <input type="text" placeholder="line" matInput formControlName='line'>
  </mat-form-field>

</div>

<h4>Home Phone</h4>
<div formGroupName='homePhone'>
  <mat-form-field>
    <input type="text" plcaeholder='area' matInput formControlName='area'>
  </mat-form-field>

  <mat-form-field>
    <input type="text" placeholder="prefix" matInput formControlName='prefix'>
  </mat-form-field>

  <mat-form-field>
    <input type="text" placeholder="line" matInput formControlName='line'>
  </mat-form-field>

</div>

Whenever i change value in any form-group, it is getting updated in another. Please help.

slackblitz is slackblitz

1 Answer 1

1

It's because you're using the same fb.group instance via the phone constant:

This should work :

    constructor(private fb: FormBuilder) { 

    this.myForm = this.fb.group({
      email: '',
      homePhone: this.createFormGroup(),
      cellPhone: this.createFormGroup()
    })
  }

  createFormGroup() {
    return this.fb.group({
      area: [],
      prefix: [],
      line: []
    });
  }

I've updated your slackblitz

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

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.