编辑版本:
https://stackblitz.com/edit/angular-reactive-forms-atvaym
模板:
<form [formGroup]="SignupForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="username">UserName</label>
<input type="text" class="form-control" id="username" formControlName="username">
<span class="help-block" *ngIf="!SignupForm.controls.username.valid && SignupForm['controls'].username.touched">
<span *ngIf="SignupForm['controls'].username.hasError('nameIsForbidden')">name is invalid</span>
<span *ngIf="SignupForm['controls'].username.hasError('required')">field is required</span>
</span>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" formControlName="email">
<span class="help-block" *ngIf="!SignupForm.controls.email.valid && SignupForm['controls'].email.touched">
<span *ngIf="SignupForm['controls'].email.hasError('emailIsForbidden')">name is invalid</span>
<span *ngIf="SignupForm['controls'].email.hasError('required')">field is required</span>
</span>
</div>
<div class="radio" *ngFor="let gender of genders">
<label>
<input type="radio" [value]="gender" formControlName = "gender">{{gender}}
</label>
</div>
<div formArrayName="hobbies">
<h4>Hobbies</h4>
<button class="btn btn-default" type="button" (click)="onAddHobby()">Add Hobby</button>
<div class="form-group" *ngFor="let hobbyControl of SignupForm['controls'].hobbies['controls']; let i=index">
<div [formGroupName]="i">
<div [formGroup]="SignupForm['controls'].hobbies['controls'][i]">
<input type="text" class="form-control" formControlName="name">
</div>
</div>
</div>
</div>
<span class="help-block" *ngIf="!SignupForm.valid && SignupForm.touched">please enter valid data</span>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
ngOnInit(){
this.SignupForm = this.fb.group({
username: [{value: 'default name', disabled: false}, [Validators.required, this.validateName()]],
email: [{value: 'default name', disabled: false}, [Validators.required, Validators.email, this.validateEmail()]],
gender: [{value: 'female', disabled: false}, [Validators.required]],
hobbies: this.fb.array([])
});
}
onAddHobby(){
const controls = <FormArray>this.SignupForm.controls['hobbies'];
let control = this.fb.group({
name: [{value: 'hobbi', disabled: false}]
});
controls.push(control);
}
private validateName(): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
for(let i of this.forbiddenUserNames){
if(i === control.value){
return {'nameIsForbidden': true};
} else {
return null;
}
}
}
}
private validateEmail(): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
if(control.value === 'test@test.com'){
return {'emailIsForbidden': true};
} else {
return null;
}
}
}
我建议看一下这篇关于异步验证器的文章
https://alligator.io/angular/async-validators/