错误:找不到路径控制:'x'angle 2

时间:2017-07-05 20:12:24

标签: html angular angular2-forms

我正在尝试在整个表单中创建一个特定的表单字段动态,以便可以将x个对象添加到该字段的数组中。 但是,每次页面都会出现

错误:找不到路径控件:'media - > “

这是我的form.ts

this.cardForm = new FormGroup({
  'title': new FormControl(cardTitle),
  media: this._fb.array([
    this.initMedia(),
  ]),
  'links': new FormGroup({
    'news': new FormControl(news),
  }),

  initMedia() {
   return this._fb.group({
   type: new FormControl(),
   raw: new FormControl(),
   primary: new FormControl(),
   thumbs: this._fb.group({
    default: new FormControl()
  })
})
}

addMedia(){
 const control = <FormArray>this.cardForm.controls['media'];
 control.push(this._fb.control(['']));
}
removeMedia(i: number){
 const control = <FormArray>this.cardForm.controls['media'];
 control.removeAt(i);
}

这是我的form.html:

<div class="row">
  <div class="col-xs-12">
    <form [formGroup]="cardForm" (ngSubmit)="onSubmit(cardForm.value)">
      <div class="row">
        <div class="col-xs-12">
          <button
            type="submit"
            class="btn btn-success">
            Update Card</button>
          <button
            type="button"
            class="btn btn-danger"
            (click)="onCancel()">
            Cancel</button>
        </div>
      </div>

    <div formArrayName="media">
      <div class="row">
        <div class="col-xs-12">
          <div class="form-group">
            <div *ngFor= "let media of cardForm.controls.media.controls; let i=index">
              <span>Media {{i + 1}}</span>
              <span *ngIf="cardForm.controls.media.controls.length > 1" (click)="removeMedia(i)"></span>
          </div>
          <div [formGroupName]="i">
            <div>
              <label>Url</label>
                <md-input-container class="mdcontainer">
                  <input mdInput placeholder="Media Url" type="text" formControlName="raw">
                </md-input-container>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

媒体[]看起来像这样:

media: [
        {
          raw:'string',
          primary: boolean,
          type: 'string',
          thumb: {
                 default: 'string'
                 {
        }
      ]

我错过了什么/做错了这个错误出现了? 任何帮助/提示/建议将不胜感激。

2 个答案:

答案 0 :(得分:3)

[formGroupName]="i"应位于*ngFor内。在这种情况下,i变量将具有非undefined

<div *ngFor="let media of cardForm.controls.media.controls; let i=index">
  <span>Media {{i + 1}}</span>
  <span *ngIf="cardForm.controls.media.controls.length > 1" (click)="removeMedia(i)"></span>
  <div [formGroupName]="i">
    <div>
      <label>Url</label>
      <md-input-container class="mdcontainer">
        <input mdInput placeholder="Media Url" type="text" formControlName="raw">
      </md-input-container>
    </div>
  </div>
</div>

<强> Plunker Example

答案 1 :(得分:0)

您可以尝试使用get方法。我认为它更加用户友好:

cardForm.get('media')

请在此处的文档中查看:https://angular.io/guide/reactive-forms#inspect-formcontrol-properties