6

I am trying to add a formGroup to my overall form conditional on a specific field being of a certain type in my case. My function to add this formGroup looks like this:

  initSocial() {
      const group = <FormGroup>this.cardForm;
        group.addControl(
          'social': this._fb.group({
            'fb': new FormControl(this.currentCard.social.fb),
            'yt': new FormControl(this.currentCard.social.yt),
            'ig': new FormControl(this.currentCard.social.ig),
            'tw': new FormControl(this.currentCard.social.tw),
          })
        )
  }

Right now I am getting a typescript error under the colon after 'social' saying a ',' is expected. I haven't been able to test this to see if addControl() will even work.

My function to fire initSocial is in ngOnInit and looks like this:

      if(this.currentCard.cardType === "brand"){
        this.initSocial();
      }

Any help/tips/suggestions would be much appreciated.

Brian Stanley
  • 2,078
  • 5
  • 24
  • 43
  • you are missing `{}` around `'social'`. Please don't post "why this code doesn't work" kind of questions. – Reactgular Jul 20 '17 at 13:55
  • that could also help: https://stackoverflow.com/questions/55334283/reactive-forms-how-to-add-new-formgroup-or-formarray-into-an-existing-formgroup –  Mar 25 '19 at 11:59

1 Answers1

5

addControl() function looks like:

/**
 * Add a control to this group.
 * @param {?} name
 * @param {?} control
 * @return {?}
 */
FormGroup.prototype.addControl = function (name, control) {
    this.registerControl(name, control);
    this.updateValueAndValidity();
    this._onCollectionChange();
};

and expects 2 arguments: name and control, separated by comma. So, just try to replace semicolon (:) after 'social' with comma (,):

group.addControl('social', this._fb.group({
  fb: this.currentCard.social.fb,
  yt: this.currentCard.social.yt,
  ig: this.currentCard.social.ig,
  tw: this.currentCard.social.tw,
}))

also, you do not need new FormControl(DEFAULT_VALUE), form builder does it already

Andriy
  • 14,781
  • 4
  • 46
  • 50