在Angular2中有条件地向另一个formGroup添加formGroup

6

我正在尝试在特定字段的类型为某种类型时,向整个表单添加一个formGroup。我的添加formGroup的函数如下:

  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),
          })
        )
  }

现在,在“social”后面的冒号下,我收到了一个TypeScript错误,说期望有一个“,”。我还没有能够测试这个,看看addControl()是否会起作用。

我的触发initSocial的函数在ngOnInit中,代码如下:

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

非常感谢您的帮助、提示和建议。

你忘记在 'social' 周围加上 {} 了。请不要发布类似于“为什么这段代码不起作用”的问题。 - Reactgular
这也可能有所帮助:https://dev59.com/clMI5IYBdhLWcg3wyurE - user3025289
1个回答

5

addControl() 函数的样子如下:

/**
 * 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();
};

并且期望有两个参数:namecontrol,用逗号分隔。 因此,请尝试将“social”后面的分号 (:) 替换为逗号 (,):

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,
}))

此外,您不需要使用new FormControl(DEFAULT_VALUE),因为表单构建器已经处理了它。

天啊!这太简单了。这让函数正常工作了。谢谢@Andriy! - Brian Stanley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接