我很难在表单中同时使用 *ngIf 和 ngFormModel 来验证所述表单。
用例是这样的:根据用户输入,隐藏或停用表单中的某些特定字段。但如果显示这些输入,则必须对其进行验证。
当只需要基本验证时,我可以采取一种或另一种方式:
- 如果仅需要输入,则使用 A-OK
ngControl
和required
- 如果需要特定格式,则可以使用该
pattern
属性。它不是 Angular,但它有效。
但是为了实现更复杂的验证,我一直在尝试使用ngControl
耦合ngFormModel
来使用自定义检查。我使用了以下页面上的代码片段:
如何在 angular2 中添加表单验证模式(以及那里引用的链接)
Angular2 表单:验证、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 type="submit" class="btn btn-primary" [disabled]="!formState.form.valid">I can't be enabled without accessing the input :(</button>
<button type="submit" class="btn btn-default">Submit without using form.valid (boo !)</button>
</form>
</div>
打字稿
import {Component, ChangeDetectorRef, AfterViewInit } from 'angular2/core';
import {NgForm, FormBuilder, Validators, ControlGroup, FORM_DIRECTIVES} from 'angular2/common';
@Component({
selector: 'accueil',
templateUrl: 'app/accueil.component.bak.html',
directives:[FORM_DIRECTIVES],
providers: [FormBuilder]
})
export class AccueilComponent implements AfterViewInit {
private myForm: ControlGroup;
model: any;
constructor(fb: FormBuilder, cdr: ChangeDetectorRef) {
this.cdr = cdr ;
this.model = {} ;
this.myForm = fb.group({
"hideField": [false],
"optionalField": [this.model.optionalField, Validators.compose([this.myCustomValidator])]
});
}
ngAfterViewInit() {
// Without this, I get the "Expression has changed after it was checked" exception.
// See also : https://stackoverflow.com/questions/34364880/expression-has-changed-after-it-was-checked
this.cdr.detectChanges();
}
submitForm(){
alert("Submitted !");
}
myCustomValidator(optionalField){
// Replace "true" by "_someService.someCheckRequiringLogicOrData()"
if(true) {
return null;
}
return { "ohNoes": true };
}
}
即使使用 *ngIf 从模板中删除了输入,构造函数仍然在引用控件。这反过来又阻止了我使用 [disabled]="!formState.form.valid",这myForm
是可以理解的 INVALID。
我的目标是使用 Angular 2 吗?我确信这不是一个不常见的用例,但是根据我目前的知识,我看不出如何使它工作。
谢谢 !