我很难在表单中使用*ngIf和ngFormModel来验证表单.
用例是这样的:根据用户输入,隐藏或停用表单中的某些特定字段.但是如果显示这些输入,则必须对它们进行验证.
当只需要基本验证时,我可以这样或那样做:
ngControl和使用A-OKrequiredpattern属性.它不是Angular,但它有效.但是为了实现更复杂的验证,我一直在尝试使用ngControl耦合ngFormModel来使用自定义检查.我使用了以下页面中的代码片段:
如何在angular2中添加表单验证模式(以及那里引用的链接)
Angular2表单:Validations,ngControl,ngModel等
我的代码如下:
HTML
<div>
<h1>Rundown of the problem</h1>
<form (ngSubmit)="submitForm()" #formState="ngForm" [ngFormModel]="myForm">
<div class="checkbox">
<label>
<input type="checkbox" [(ngModel)]="model.hideField" ngControl="hideField"> Is the input below useless for you ?
</label>
</div>
<div *ngIf="!model.hideField">
<div class="form-group">
<label for="optionalField">Potentially irrelevant field </label>
<input type="text" class="form-control" [(ngModel)]="model.optionalField" ngControl="optionalField" required #optionalField="ngForm">
<div [hidden]="optionalField.valid || optionalField.pristine" class="alert alert-warning">
This input must go through myCustomValidator(), so behave.
</div>
</div>
</div>
<button …Run Code Online (Sandbox Code Playgroud)我正在使用FormArrays来处理可变长度的对象数组.虽然我当前的实现主要起作用,但在验证方面我遇到了问题,因为对FormArray所做的任何更改都不会传播到其"父"FormGroup ...或者至少不会自动更新FormGroup的值可以更新,通过更改由所述FormGroup管理的另一个控件的值.
在这一点上,我无法判断我的实现是否有问题,或者我是否期待我不应该做的事情......无论"问题"到底是什么,我都很乐意接受任何意见.这点.
链接到Plunker:https://plnkr.co/edit/PLslyJo1YOszGwTpujyx (Angular版本是2.0.1)
Plunker app.ts顶部的评论详细说明了重现问题的步骤(或者对我来说有什么问题).
当链接到Plunker时SO要求一些代码,这里是与FormGroup和FormArray的定义有关的行
this.form = this.fb.group({
"size":[0, Validators.required],
"someArray": this.fb.array(this.initFormArray(0), Validators.required),
"someOtherField":[null]
});
initFormArray(size:number):FormGroup[]{
let newFormArray:FormGroup[] = [] ;
for(let i = 0 ; i < size ; i++){
newFormArray.push(this.fb.group({
fieldA: [null, Validators.required],
fieldB: [null, Validators.required]
}));
}
return newFormArray;
}
updateFormArray(value:string){
let newSize:number = parseInt(value) ;
if(newSize >= 0){
this.form.controls["someArray"] = this.fb.array(this.initFormArray(newSize))
this.form.updateValueAndValidity();
}
}
Run Code Online (Sandbox Code Playgroud)
这是在Plunker中说明的,但我在这里可能会提到订阅FormArray的valueChanges似乎没有帮助(或者我在订阅中没有做正确的事情):
this.form.controls['someArray'].valueChanges.subscribe((data) => this.form.updateValueAndValidity());
Run Code Online (Sandbox Code Playgroud)
感谢任何人在ch :)
编辑(2016-10-11):玩弄valueChanges钩子更能让我实际上解决问题,但解决方案不尽如人意.出于这个原因,我正在编辑而不是回答我自己的问题,但如果任何mod认为这是一个有效的结论,请务必做你认为合适的事情.
至于我的"解决方案":不是订阅valueChangesFormArray或根FormGroup级别,我几乎可以通过订阅 …