我很难在表单中使用* ngIf和ngFormModel来验证表单。
用例是这样的:根据用户输入,隐藏或停用表单中的某些特定字段。但是如果显示这些输入,则必须对它们进行验证。
当只需要基本验证时,我可以这样或那样做:
ngControl
和required
pattern
属性。它不是Angular,但它有效。但是为了实现更复杂的验证,我一直在尝试使用与ngControl
耦合的ngFormModel
来使用自定义检查。我使用了以下页面中的代码片段:
How to add form validation pattern in angular2(以及那里引用的链接)
Angular2 Forms :Validations, ngControl, ngModel etc
我的代码如下:
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
可以理解为无效。
我的目标是使用Angular 2吗?我确信这不是一个不常见的用例,但是再次根据我目前的知识,我看不出我是如何使它工作的。
谢谢!
答案 0 :(得分:8)
您可以尝试执行的操作是重置控件上的验证程序。这意味着,当您希望由于状态更改而将一组新的验证器绑定到控件时,您将重新定义验证器函数。
在您的情况下,选中/取消选中复选框后,您需要执行以下操作:
form.valid
。See my plnkr sample based on Angular.io's Forms Guide
if (optional)
this.heroFormModel.controls['name'].validator = Validators.minLength(3);
else
this.heroFormModel.controls['name'].validator =
Validators.compose([Validators.minLength(3), Validators.required]);
this.heroFormModel.controls['name'].updateValueAndValidity();
答案 1 :(得分:2)
答案 2 :(得分:0)
这是RC4的更新版本。为了我的目的,我也将它重命名为npControl。
import { Directive, Host, OnDestroy, Input, OnInit } from '@angular/core';
import { ControlContainer } from '@angular/forms';
@Directive({
selector: '[npControl]'
})
export class NPControlDirective implements OnInit, OnDestroy {
@Input() npControl: string;
constructor(@Host() private _parent: ControlContainer
) { }
ngOnInit(): void {
console.log('include ', this.npControl);
setTimeout(() => this.formDirective.form.include(this.npControl));
}
ngOnDestroy(): void {
console.log('exclude ', this.npControl);
this.formDirective.form.exclude(this.npControl);
}
get formDirective(): any {
return this._parent;
}
}