Angular2表单生成器,具有异步调用的结果

时间:2017-02-01 19:04:17

标签: angular typescript

我是在异步调用的结果后创建我的表单,但我仍然坚持我应该如何将异步调用的结果传递给表单生成器

这就是我试过的

export class PerformInspectionPage implements OnInit {
 checklists: any;
 inspectionform: FormGroup;

 ngOnInit(): any {
    this.checklists  = this.onGetItems(); //this is where i fetch the data not sure of
                                        //another way to use.

 let checkinputs: FormArray = new FormArray([]);

 for (let i = 0; i < this.checklists.length; i++) {
   checkinputs.push(
    new FormGroup({
      description:new FormControl(this.checklists[i].item),
      input: new FormControl(''),
      yesradio: new FormControl(''),
      noradio: new FormControl(''),
    })
  )
}

this.inspectionform = this._formBuilder.group({
  inputfileds: this._formBuilder.array(checkinputs.controls)
})

 }

现在获取仍在同一组件上的项目的函数

 onGetItems(){

    return this._inspectionService.getChecklists()
       .subscribe(
          res=> {
           this.checklists = res;
          },

       );


      }

当我检查console.log(this.inspectionform);它有一个0项的数组。我如何修改它以返回结果异步调用

我也试过

  return this._inspectionService.getChecklists(this.truckParam)
  .subscribe(
    res=> {
      let checkinputs: FormArray = new FormArray([]);

      for (let i = 0; i < this.checklists.length; i++) {
        checkinputs.push(
       new FormGroup({
          description:new FormControl(this.checklists[i].item),
           input: new FormControl(''),
           yesradio: new FormControl(''),
          noradio: new FormControl(''),
        })
     )
    }

    this.inspectionform = this._formBuilder.group({
       inputfileds: this._formBuilder.array(checkinputs.controls)
    })
      },

  );

问题在于formbuilder的实例在表单

上永远不可见

那是

在表格上

 <form [formGroup]="inspectionform" #newform > //this returns an error of

 formGroup expects a FormGroup instance. Please pass one

1 个答案:

答案 0 :(得分:1)

由于您要异步构建表单MODEL ,因此还需要异步显示表单TEMPLATE

当前代码(您显示的第二个选项)的问题是Angular在您构建模型之前尝试显示表单。

尝试这样的事情:

getChecklists(...)

  .subscribe(() => {

    // Build the form model like you currently do.
    this.inspectionForm = this._formBuilder.group({...});

    // Then, set some kind of flag to indicate that the form is ready.
    this.isFormReady = true;

  });

在模板中:

<form *ngIf="isFormReady" [formGroup]="inspectionForm" #newform>

实际上,您可能只能跳过isFormReady标志并直接测试inspectionForm属性的值:

<form *ngIf="inspectionForm" [formGroup]="inspectionForm" #newform>