2016-09-20 209 views
0

我收到以下錯誤,當我嘗試啓動我ngOnInit方法表單控件值:設置默認表單值

錯誤

formGroup expects a FormGroup instance. Please pass one in. 

方法

ngOnInit() { 
    this.getBusinessData().then((response:any) => { 
     this.businessForm = this.formBuilder.group({ 
      'business_name': [response.data.business_name, Validators.required], 
      'email': [response.data.email, Validators.required] 
     }); 
    }); 
} 

我能夠通過使用setValue來解決這個問題,在從我的API服務調用中返回一個承諾之後所以它的工作原理:

ngOnInit() { 
     // Build the form 
     this.businessForm = this.formBuilder.group({ 
      'business_name' : ['', Validators.required], 
      'email' : ['', Validators.required], 
     }); 
     // Fetch data for the view 
     this.getBusinessData().then((response:any) => { 
      this.businessForm.setValue({ 
       business_name: response.data.business.business_name, 
       email: response.data.business.email 
      }); 
     }); 
    } 

但似乎並不是最好的方法。我應該如何將從API返回的數據綁定到表單控件?看起來我不應該使用formGroups,並且可能只是使用ngModels將數據綁定到表單上?

UPATE: 與micronyks方法,我試過如下:

ngOnInit() { 
     // Bind data to the form 
     this.getBusinessData().then((response:any) => { 
      this.businessForm = this.formBuilder.group({ 
       'business_name' : [response.data.business.business_name==undefined?'': response.data.business.business_name, Validators.required], 
       'email' : [response.data.business.email==undefined?'': response.data.business.email, Validators.required] 
      }); 
     }); 
    } 

但它在控制檯返回以下錯誤:

EXCEPTION: Uncaught (in promise): Error: Error in edit.template.html:12:10 caused by: formGroup expects a FormGroup instance. Please pass one in. 

這似乎發生時,它被包裹圍繞API調用。 這個的值是否被覆蓋?

+0

它工作?如果是這樣,你只想知道最好的方法嗎? – micronyks

+0

@micronyks我的第二種方法的作品,但我正在尋找一個更乾淨的解決方案。我覺得必須有比在formGroup對象上運行setValue方法更好的方法。在我的API調用中解析出承諾後,是否有辦法綁定formBuilder構造函數中的數據?當我嘗試 –

+0

時,我不斷收到上面提到的錯誤,但我還沒有嘗試過,但您可以試試這個:this.businessForm = this.formBuilder.group({business_object_name:[response.data.business.business_name == undefined?'':response.data.business.business_name,Validators.required], ... });' – micronyks

回答

2

您需要在angular2呈現視圖之前設置this.businessForm實例。 Solution_1:只有在設置了formBuilder的實例後,才使用* ngIf來顯示錶單。 Solution_2:使用默認值設置formbuilder this.businessForm,然後在獲取API響應時更新表單。