首页 文章

嵌套的FormGroup angular5不起作用

提问于
浏览
0

我在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>

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

slackblitz是slackblitz

1 回答

  • 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

相关问题