我的表单按以下方式制作:
<form #form="ngForm" novalidate (ngSubmit)="register(form);">
<div class="registerinput">
<label for="firstname">First Name</label>
<input #firstname="ngModel" type="text" name="firstname" maxlength="30" pattern="[a-zA-Z ]*" required ngModel>
<div [hidden]="!form.controls.firstname.touched && !form.controls.firstname.errors?.required" class="alert-danger">
Please enter your name
</div>
<div [hidden]="!form.controls.firstname.touched && !form.controls.firstname.errors?.maxlength" class="alert-danger">
Max length is 30 characters
</div>
<div [hidden]="!form.controls.firstname.touched && !form.controls.firstname.errors?.pattern" class="alert-danger">
Only letters are allowed
</div>
</div>
<div class="registerinput">
<button type="submit" class="btn-register">Register</button>
</div>
</form>
我收到以下错误:
EXCEPTION: Uncaught (in promise): Error: Error in http://localhost:3000/app/register/register.component.html:7:17 caused by: Cannot read property 'touched' of undefined
Error: Error in http://localhost:3000/app/register/register.component.html:7:17 caused by: Cannot read property 'touched' of undefined
似乎无法找到我的控件。但是,当我尝试打印form.controls时,我得到以下结果:
所以在这种情况下,它发现它们很好。这里有什么问题?我过去曾做过类似的工作。
更新:我发现代替form.controls.firstname.touched
而不是firstname.touched
,我必须使用form.controls.*
来访问它们。我只是不明白为什么,因为我在同一个项目中有另一个文件,我使用的格式完全相同,但在那个文件中我使用的是firstname.touched
。如果您已声明模板引用变量,我想您可以使用form.controls.*
,但我不知道在哪种情况下您可以使用{{1}}。
答案 0 :(得分:2)
另一种验证方法是:
<form #form="ngForm" novalidate (ngSubmit)="register(form);">
<div class="registerinput">
<label for="firstname">First Name</label>
<input #firstname="ngModel" type="text" name="firstname" maxlength="30" pattern="[a-zA-Z ]*" required ngModel>
<div [hidden]="!firstname.touched && !firstname.errors?.required" class="alert-danger">
Please enter your name
</div>
<div [hidden]="!firstname.touched && !firstname.errors?.maxlength" class="alert-danger">
Max length is 30 characters
</div>
<div [hidden]="!firstname.touched && !firstname.errors?.pattern" class="alert-danger">
Only letters are allowed
</div>
</div>
<div class="registerinput">
<button type="submit" class="btn-register" [disabled]='!form.valid'>Register</button>
</div>
</form>
这是一个非常简单易行的方法。