angular2 - 数据未以嵌套形式显示

时间:2017-07-24 00:09:15

标签: angular angular-forms

首先,我已经阅读了很多关于嵌套表单的stackoverflow的答案,但我无法解决这些问题,谢谢你的时间。

我正在尝试使用表单来编辑用户的信息,我使用的信息是这样的:

(2) [Object, Object]
  0: Object
    mail: "example1@exp.exp"
  1: Object
    mail: "example2@exp.exp"

在我的组件中,我创建了一个嵌套表单:

// blablabla.component.ts

// imports, component, ...

export class EditMailsComponent implements OnInit {
  @Input() data: Array<any>;

  private form: FormGroup;

  constructor(
    private formBuilder: FormBuilder
  )

  ngOnInit(){
    this.form = this.formBuilder.group({
      mails: this.formBuilder.array([]),
    });

    this.fnOpen();
  }

  private fnOpen()
  {
    // ...

    const control = <FormArray>this.form.controls['mails'];

    this.data.forEach(x => {
      control.push(this.populateForm(x);
    });

    // ...
  }

  private populateForm(x: Array<any>)
  {
    return this.formBuilder.group({
      mail: [x.mail]
    });
  }
}

我的html文件如下所示:

<!-- ... -->
<form class='smart-form' novalidate>
  <div class='modal-body'>
    <div [formGroup]='form'>
      <div formArrayName='mails'>
        <div *ngFor='let mail of form.controls.mails.controls; let i=index'>
          <div [formGroupName]="i">
            <fieldset>
              <section class='col-col-6'>
                <label class='input' id='mail'>
                  <input type='text' formControlName='mail' ngModel>
                </label>
              </section>
            </fieldset>
      <!-- ... --> 

当我尝试打开要编辑的页面时,会创建正确数量的嵌套表单(例如:如果我有一个4个对象数组,则打开4个表单)但是“mail”不会显示在其中。

有人能告诉我我失踪的地方吗?

如果您需要更多信息,我将很乐意为您提供帮助。

更新

我去过的地方,然后问:

  1. STACKOVERFLOW - Angular 2 Form “Cannot find control with path”
  2. STACKOVERFLOW - Angular 2 Form “Cannot Find Control”
  3. STACKOVERFLOW - Cannot find control with path: angular2
  4. STACKOVERFLOW - Angular 2 Accessing Nested FormArrays using FormBuilder
  5. 教程(我尝试使用它们来查找代码中的错误):

    1. How to Build Nested Model-driven Forms in Angular 2
    2. Angular2: Building nested, reactive forms

1 个答案:

答案 0 :(得分:1)

使用结构中的数据:

[
  {
    "mail": "example1@exp.exp"
  },
  {
    "mail": "example2@exp.exp"
  }
]

父组件

ngOnInit() {
    this.myForm = this._fb.group({
        name: ['', [Validators.required, Validators.minLength(5)]],
        mails: this._fb.array(this.mails.map(mail => this._fb.group(mail)))
    });
}

父模板

<form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm)">
  <ng-container *ngFor="let mail of myForm.controls.mails.controls">
    <mail [group]="mail"></mail>
  </ng-container>
</form>

子组件

@Component({
  moduleId: module.id,
  selector: 'mail',
  templateUrl: 'mail.component.html',
})
export class MailComponent {
  @Input('group')
  public mailForm: FormGroup;
}

子模板

<div [formGroup]="mailForm">
  <div class="form-group">
    <label>mail</label>
    <input type="text" class="form-control" formControlName="mail">
  </div>
</div>

Live plunker example