我按照角度2教程尝试以角度2形式实现验证。见代码:
<form #loginForm="ngForm" (ngSubmit)="login()">
<div>
<label for="email">Email:</label>
<input type="text" id="email" name="email" required minlength="4" maxlength="24" [(ngModel)]="emailField" #name="ngModel" />
<div *ngIf="email?.errors && (email?.dirty || email?.touched)" class="alert alert-danger">
<div [hidden]="!email.errors.required">
email is required
</div>
<div [hidden]="!email.errors.minlength">
email must be at least 4 characters long.
</div>
<div [hidden]="!email.errors.maxlength">
Name cannot be more than 24 characters long.
</div>
</div>
</div>
<div>
<label>Password:</label><input type="password" name="password" [(ngModel)]="passwordField" />
</div>
<div>
<button [disabled]="!loginForm.form.valid" type="submit">Submit</button>
</div>
</form>
问题是我收到此错误代码:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'errors' of undefined
我尝试完全按照官方网站上的教程实现它:https://angular.io/docs/ts/latest/cookbook/form-validation.html#!#template1
答案 0 :(得分:2)
答案(感谢George K)是我不小心写了#name="ngModel"
而不是#email="ngModel"