本文實例為大家分享了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; } }
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com