嵌套FormGroup angular5无法正常工作

时间:2018-07-20 06:49:05

标签: angular

我正在angular6应用程序中使用嵌套表单组。

 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>

每当我在任何表单组中更改值时,它都会在另一个表单组中更新。请帮忙。

slackblitz是slackblitz

1 个答案:

答案 0 :(得分:1)

这是因为您通过电话常量使用了相同的fb.group实例:

这应该有效:

    constructor(private fb: FormBuilder) { 

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

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

我已经更新了您的slackblitz