2017-02-01 127 views
0

的結果Angular2表單生成器正在創建我的形式的異步調用的結果之後,但我停留在我應該如何異步calll的結果傳遞給表單生成與異步調用

這是香港專業教育學院嘗試

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 
+0

'清單'看起來像什麼樣,即如何傳入數據l ook like,在這裏可能會有所幫助,看看數據是如何看起來像... – Alex

+0

傳入的數據是以json格式{id:1,item:「ddhbh」,..},{item2},... thats a json排列 –

回答

1

既然你正在構建日e 異步顯示模型,您還需要異步顯示表單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>