Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditionally add formGroup to another formGroup angular2

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.

like image 956
Brian Stanley Avatar asked Jul 20 '17 13:07

Brian Stanley


1 Answers

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

like image 136
Andriy Avatar answered Nov 17 '22 17:11

Andriy