OptiPessiProgrammer
OptiPessiProgrammer

Reputation: 2336

Setting default form object value from async call in Angular 2 using FormBuilder

I'm using "@angular/forms": "~2.1.0" and "angular-cli": "1.0.0-beta.19-3" and am trying to set the default value of my FormGroup's (campaignForm) campaign_config_id attribute after I've made an async call to get a list of campaignConfigs.

I've tried using the following as per another SO suggestion but I get TypeError: _this.campaignForm.controls.campaign_config_id.updateValue is not a function.

this.campaignConfigService.getCampaignConfigs()
  .subscribe(
    campaignConfigs => {
      ...
      this.campaignForm.controls['campaign_config_id'].updateValue(campaignConfigs[0].id)
    }
  );

I've also tried casting this.campaignForm.controls['campaign_config_id'] into a NgControl, FormControl, SelectControlValueAccessor and other objects but none of them have an .updateValue function.

Any suggestions on how to best do this?

Upvotes: 1

Views: 1724

Answers (2)

LuisKx
LuisKx

Reputation: 312

I think the most flexible way to deal with forms is using the "ReactiveForms" and create the form with the FormBuilder class.

Please study about reactive forms and FormGroup/FormBuilder and in the end you can do something like this: this.form.controls['campaign_config_id'].setValue(yourIdValue)

Upvotes: 5

Harry Ninh
Harry Ninh

Reputation: 16728

updateValue() is deprecated. Use setValue() instead for all kind of form controls.

Upvotes: 4

Related Questions