【发布时间】:2017-11-09 23:54:02
【问题描述】:
我有以下型号:
export interface Content {
lang: string;
title: string;
}
我需要验证这个contents FormArray 的parent FormGroup:
this.formBuilder.group({
defaultLang: ['', Validators.required],
contents: this.formBuilder.array([], Validators.minLength(1))
});
对于我的contents FormArray 中的每个Content,我使用以下content FormGroup 验证模型:
this.formBuilder.group({
lang: ['', Validators.required],
title: ['', Validators.required]
});
现在,我将以下content FormGroup 添加到我的contents FormArray 以验证每个Content:
(<FormArray>parentFormGroup.controls['contents'])
.push(this.contentFormGroup);
但使用这种方法我无法验证这些规则:
- 如果
Content字段之一已填满,则会进行内容验证(这意味着将content FormGroup添加到contents FormArray) - 如果没有填写任何内容字段,则不会进行内容验证(这意味着删除
contents FormArray的content FormGroup如果存在) - 如果
Content的lang是parent FormGroup的defaultLang,则该内容为必填项。
问题
是否有解决方法可以仅使用验证器添加/删除contents FormArray 的content FormGroup?
有没有办法只使用 Angular 原生验证器?
我需要创建自定义验证器吗?如果是,你有没有很好的例子来说明FormArray?
【问题讨论】:
-
你能创建一个 plunker 吗?我在拼凑这段代码时遇到了一些麻烦? :)
标签: angular validation angular2-forms