<一>模版表单
1.
<form #myForm='ngForm'><form>
相对于传统表单来说 少了一个action属性
此过程中 使用ngForm表示 angular框架会来接手处理此表单
#myForm是模版变量;
2.取值
<form #myForm='ngForm' (ngSubmit)='onSubmit(myForm.value)'>
<input ngModel type='text' name='username'>
<form>
输出 username:'xxx'
/******除此之外还可以这样获取input的值*****/
<input type='text' #val /><button (click)='onclick(val.value)'></button>
3.group
<form #myForm='ngForm' (ngSubmit)='onSubmit(myForm.value)'>
<input ngModel type='text' name='username'>
<ng-container ngModelGroup='info'>
<input type='text' ngModel name='pwd1'>
<input type='text' ngModel name='pwd2'>
</ng-container>
<form>
输出
{
username:'xxx',
info:{
pwd1:'xxx',
pwd2:'xxx'
}
}
4.模版表单的验证
//第一种方式
<form #myForm='ngForm' (ngSubmit)='onSubmit(myForm.value)'>
<input ngModel type='text' name='username' required>
<div [hidden]='!myForm.form.hasError('required','username')'>
username is required
</div>
<form>
//第二种方式
<form #myForm='ngForm' (ngSubmit)='onSubmit(myForm.value)'>
<input #username='ngModel' type='text' name='username' required>
//如果名字已经填写或者名字为初始值,则隐藏;
//<div [hidden]='username.valid||username.pristine'>
// username is required
//</div>
//如果验证不通过并且这个输入框有被触摸或者改变,如果这个值没有填写 则出提示
<div *ngIf='username.invalid&&(username.touched||username.dirty)'>
<div *ngIf='username.errors.required'>
username is required yet
</div>
</div>
<form>
<二>响应式表单
1.创建一个响应式表单组件
2.在typescript中声明一个formModel:FormGroup 用来管理整个表单(可以看作一个后台容器)
<form [formGroup]='formModel'> <input type="text" name="username" id="username" formControlName="username"/> <div [hidden] = "formModel.get('username').valid"> <div class="form-validate" [hidden]="!formModel.hasError('required','username')">用户名不能为空</div> <div class="form-validate" [hidden]="!formModel.hasError('minlength','username')">用户名长度不少于6位</div> </div> <div class="form-control height68" formGroupName="passwords"> <div> <label for="password">密码:</label> <input type="password" name="password" id="password" formControlName="password"> </div> <div class="form-validate" [hidden]="!formModel.hasError('minlength',['passwords','password'])"> 密码长度不低于6位 </div> <div> <label for="confirmPass">确认密码:</label> <input type="password" name="confirmPass" id="confirmPass" formControlName="confirmPass"/> </div> </div> <div class="form-validate" [hidden]="!formModel.hasError('equal','passwords')"> {{formModel.getError('equal','passwords')?.desc}} </div> </form> ts: export class rxfComponent{ formModel:FormGroup; //Formbuilder是我们可以采用的另一种方式来创建Form,这种方式是以模型驱动完成的,更适合我们进行编码控制,有利于我们将逻辑与视图分离。 constructor(fb:FormBuilder){ this.formModel=fb.group({ username:['初始值',[Validators.required,Validators.minlength(11)]], passwords:fb.group({ password: ['123456',Validators.minLength(6)], confirmPass:['123456'] },{ validator:equalValidator }) }) } //equalValidator. 此处是一个函数 }