我正在为电子邮件编写表单验证,并且它给出以下错误-错误TypeError:无法读取null的属性“ email”。 以下是Angular 5模板驱动表单的HTML代码。
<form name="form" #myForm="ngForm" (ngSubmit) = "onSubmit()">
<div class="form-group">
<label for="firstName">First Name*</label>
<input type="text" class="form-control" name="firstName" [(ngModel)]="firstName" #firstname="ngModel" required minlength="6" />
<div *ngIf="firstname.touched && firstname.invalid">
<div *ngIf="firstname.invalid && firstname.errors.required" class="alert alert-danger">First name is mandatory</div>
<div *ngIf="firstname.invalid && firstname.errors.minlength" class="alert alert-danger">First name must have minimum 6 characters</div>
</div>
<div *ngIf="myForm.submitted && firstname.invalid">
<div *ngIf="firstname.invalid && firstname.errors.required">First name is mandatory</div>
</div>
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" class="form-control" name="lastName" [(ngModel)]="lastName" #lastname="ngModel" required />
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" name="myemail" [(ngModel)]="email"
#myemail="ngModel" required myemail/>
<div *ngIf="myemail.touched">
<div *ngIf="myemail.invalid && myemail.errors?.required" class="alert alert-danger">Email is required</div>
<div *ngIf="myemail.errors.email && !myemail.errors.required" class="alert alert-danger">Email is not valid</div>
</div>
</div>
<div class="form-group">
<label for="selectcity">City</label>
<select name="city" class="form-control" [(ngModel)] = "cityvalue" required #cityselect = "ngModel">
<option value="Pune">Pune</option>
<option value="Mumbai">Mumbai</option>
<option value="Delhi">Delhi</option>
<option value="Surat">Surat</option>
</select>
<div *ngIf="cityselect.touched && cityselect.invalid">
<div *ngIf="cityselect.invalid && cityselect.errors.required" class="alert alert-danger">City name is mandatory</div>
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" [(ngModel)]="password" #mypassword="ngModel" minlength="6"/>
</div>
<div class="form-group">
<button class="btn btn-primary">Register</button>
</div>
</form>
以下是电子邮件验证的代码
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" name="myemail" [(ngModel)]="email"
#myemail="ngModel" required myemail/>
<div *ngIf="myemail.touched">
<div *ngIf="myemail.invalid && myemail.errors?.required" class="alert alert-danger">Email is required</div>
<div *ngIf="myemail.errors.email && !myemail.errors.required" class="alert alert-danger">Email is not valid</div>
</div>
</div>
我尝试使用模式“ pattern =” [a-z0-9 ._%+-] + @ [a-z0-9 .-] +。[az] {2,4} $“”为电子邮件工作。
以下是我的问题: 为什么以模板驱动形式的角度电子邮件会引发空错误? 以及我们该如何解决。
答案 0 :(得分:0)
应更改为
<input type="email" class="form-control" name="myemail" [(ngModel)]="myemail"
#myemail="ngModel" required />