首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Angular2 FormGroup在FormArray验证中的应用

Angular2 FormGroup在FormArray验证中的应用
EN

Stack Overflow用户
提问于 2017-06-08 10:09:57
回答 1查看 1.1K关注 0票数 7

我有以下模式:

代码语言:javascript
复制
export interface Content {
  lang: string;
  title: string;
}

我需要验证这个contents FormArrayparent FormGroup

代码语言:javascript
复制
this.formBuilder.group({
  defaultLang: ['', Validators.required],
  contents: this.formBuilder.array([], Validators.minLength(1))
});

对于我的contents FormArray中的每个contents FormArray,我使用下面的content FormGroup验证模型

代码语言:javascript
复制
this.formBuilder.group({
  lang: ['', Validators.required],
  title: ['', Validators.required]
});

现在,我将以下content FormGroup添加到我的contents FormArray中,以验证每个Content

代码语言:javascript
复制
(<FormArray>parentFormGroup.controls['contents'])
    .push(this.contentFormGroup);

但是使用这种方法,我无法验证这些规则:

  • 如果一个Content字段被填充,那么就会发生内容验证(这意味着将content FormGroup添加到contents FormArray中)
  • 如果没有任何内容字段被填充,那么就不会发生内容验证(这意味着如果存在,就移除contents FormArraycontents FormArray)。
  • 如果lang of Contentparent FormGroupdefaultLang,那么内容是必需的。

问题

是否需要使用验证器来添加/删除content FormGroupcontents FormArray

是否有一种方法可以只使用角本机验证器?

我需要创建一个自定义验证器吗?如果是的话,您有什么很好的例子可以用FormArray来做吗?

EN

回答 1

Stack Overflow用户

发布于 2017-11-16 20:48:23

您可以向组中添加验证器,如下所示

代码语言:javascript
复制
 this.group = this.formBuilder.group({
        lang: ['', Validators.required],
        title: ['', Validators.required]
    });

    this.group.setValidators([          
        this.titleRequiredValidator(),
    ]);



    private titleRequiredValidator(): ValidatorFn {
        return (group: FormGroup): { [key: string]: any } => {
        const langControl = group.controls.lang;
        const titleControl = group.controls.title;

        if (langControl.value !== '' && titleControl.value == '')) {
            const error = { required: true };
            titleControl.setErrors(error);
            return error;
        }            
        else {
            titleControl.setErrors(null);
            return null;
        }
    };
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44432791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档