本文實例為大家分享了Angular模板表單校驗的方法,供大家參考,具體內容如下
1. 創建指令
ng g directive directives/mobileValidator
2. html
<form #myForm="ngForm" (ngSubmit)="onSubmit2(myForm.value, myForm.valid)"> <div> <h3>登錄</h3> </div> <div>用戶名:<input ngModel required name="username" type="text" (input)="onMobileInput(myForm)"></div> <div [hidden]="mobileValid || moblieUntouched"> <div [hidden]="!myForm.form.hasError('required','username')"> 用戶名是必填項 </div> </div> <div>電話: <input ngModel mobile name="mobile" type="text"></div> <button type="submit">登錄</button></form>
3. 控制器
mobileValid: boolean = true;moblieUntouched: boolean = true; onMobileInput(form: NgForm) { if (form) { this.mobileValid = form.form.get('mobile').valid; this.moblieUntouched = form.form.get('mobile').untouched; }}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答