本章中介绍响应式表单的创建及表单输入值的校验,对于模板表单就略过。
一、使用响应式表单的步骤
1、在模块(一般是app.module.ts)中引入ReactiveFormsModule 2、在组件的ts文件中使用响应式表单
ngOnInit() {
}
// 创建表单元素
createForm() {
this.myForm = this.fb.group({
username: ['',[Validators.required,Validators.minLength(3),Validators.maxLength(6)]],mobile: ['',[Validators.required]],password: this.fb.group({
pass1: [''],pass2: ['']
})
});
}
// 提交表单函数
postDate() {
/**
}
// 创建表单元素
createForm() {
this.myForm = this.fb.group({
username: ['',[Validators.required,Validators.minLength(3),Validators.maxLength(6)]],mobile: ['',[Validators.required]],password: this.fb.group({
pass1: [''],pass2: ['']
})
});
}
// 提交表单函数
postDate() {
/**
- valid:是否有效
- invalid:无效
- dirty:脏
- status:状态
- errors:显示错误
*/
if(this.myForm.valid){
console.log(this.myForm.value);
}
}
}
@H_301_8@
3、在组件的html页面中使用
用户名:
密码:
确认密码: