2017-01-22 55 views
0

我正尝试使用以下模板驱动窗体为anguar 2构建一个简单的验证窗体。但是,我收到以下错误消息。Angular 2检查电子邮件是否有效

error_handler.js:54 EXCEPTION:错误./LoginComponent类LoginComponent - 联模板:4:32所造成的:无法读取的不确定

财产 '有效',我相信错误是正在添加来自!email.vaid。但我不明白为什么。

<div class="col-md-6 col-md-offset-3"> 
    <h2>Login</h2> 
    <form name="form" (ngSubmit)="f.form.valid && login()" #f="ngForm" novalidate> 

     <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !email.valid }"> 
      <label for="email">Email</label> 
      <input type="email" class="form-control" name="email" [(ngModel)]="model.email" #email="ngModel" required /> 
      <div *ngIf="f.submitted && !email.valid" class="help-block">Email is required</div> 
     </div> 

     <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !password.valid }"> 
      <label for="password">Password</label> 
      <input type="password" class="form-control" name="password" [(ngModel)]="model.password" #password="ngModel" required /> 
      <div *ngIf="f.submitted && !password.valid" class="help-block">Password is required</div> 
     </div> 
    </form> 
</div> 
+0

似乎一切都还好!不知道,但你能否用'[hidden]'替换'* ngIf'并让我知道。 – micronyks

回答

1
<input type="email" class="form-control" name="email"  [(ngModel)]="model.email" #email="ngModel" required /> 

您是在模型对象.Does模型对象访问电子邮件属性存在于您的课吗? 试试这个代码

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div class="col-md-6 col-md-offset-3"> 
    <h2>Login</h2> 
    <form name="form" (ngSubmit)="f.form.valid && login()" #f="ngForm" novalidate> 

     <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !email.valid }"> 
      <label for="email">Email</label> 
      <input type="email" class="form-control" name="email" [(ngModel)]="user.email" #email="ngModel" required /> 
      <div *ngIf="!email.valid" class="help-block">Email is required</div> 
     </div> 

    </form> 
    </div> 
     `, 
    }) 
    export class App { 
    name:string; 
    user:any = { 
     email:'test' 
    } 
+0

我的实际组件中没有名称或用户电子邮件,因为我的印象是模板驱动的表单是自包含的int模板,因此对组件的任何引用都不是必需的。不过,我确实有模型:any = {};以便我可以访问表单结果。 我想一切都失败f.submitted &&!email.valid。是否因为这个“电子邮件”无法访问,因为“电子邮件”是在输入位置的较低级别声明的? – user172902

+1

现在问题在于,您正在组件中定义模型对象。您必须定义一个接口,该接口将是您的自定义类型,然后将该类型指定给模型,以便模型对象上存在email属性。它将永远是undefined.try这个plunkr [链接] https://plnkr.co/edit/W6cxKp8azRT8Lg1L8uVj?p=preview @ user172902 –

相关问题