【问题标题】:conditionally add formGroup to another formGroup angular2有条件地将 formGroup 添加到另一个 formGroup angular2
【发布时间】:2017-12-26 06:26:48
【问题描述】:

我正在尝试将 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),
          })
        )
  }

现在,在“社交”说“,”之后,冒号下出现打字错误。我无法对此进行测试以查看 addControl() 是否可以正常工作。

我的 initSocial 函数在 ngOnInit 中,如下所示:

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

任何帮助/提示/建议将不胜感激。

【问题讨论】:

标签: angular angular2-forms


【解决方案1】:

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

并需要 2 个参数:namecontrol,以逗号分隔。 因此,只需尝试用逗号 (,) 替换“社交”之后的分号 (:):

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!
猜你喜欢
  • 2017-05-21
  • 2019-07-15
  • 1970-01-01
  • 2016-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多