2017-01-22 102 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 –

相關問題