FormBuilder可以帮助我们简单优雅的新建FromGroup,并且允许对每个controller设置验证规则。本文将展示其基本用法。
首先让我们对比FormBuilder与传统方法,以展示其优越性
传统方法:
validateForm = new FormGroup({
firstname: new FormControl(null, [Validators.required]),
lastname: new FormControl(null, [Validators.required]),
email: new FormControl(null, [Validators.required])
});
使用FormBuilder:
this.contactForm = this.formBuilder.group({
firstname: [null, [Validators.required]],
lastname: [null, [Validators.required]],
email: [null, [Validators.required]]
});
import { FormBuilder } from '@angular/forms'
constructor(private formBuilder: FormBuilder) {
}
this.contactForm = this.formBuilder.group({
firstname: [''],
lastname: [''],
email: [''],
gender: [''],
isMarried: [''],
country: [''],
});
也可以添加一个或多个验证规则(validatiors)
this.contactForm = this.formBuilder.group({
firstname: ['', [Validators.required, Validators.minLength(10)]],
lastname: ['', [Validators.required, Validators.maxLength(15), Validators.pattern("^[a-zA-Z]+$")]],
email: ['', [Validators.required, Validators.email]],
gender: ['', [Validators.required]],
isMarried: ['', [Validators.required]],
country: ['', [Validators.required]],
});
快快用起来吧!