代码之家  ›  专栏  ›  技术社区  ›  raju

嵌套的FormGroup Angular5不工作

  •  0
  • raju  · 技术社区  · 6 年前

    我在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 回复  |  直到 6 年前
        1
  •  1
  •   Michael Desigaud    6 年前

    这是因为您通过电话常量使用相同的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