Angular 2检查电子邮件是否有效

时间:2017-01-22 14:56:06

标签: html angular

我正在尝试使用以下模板驱动形式为anguar 2构建一个简单的验证表单。但是,我收到以下错误。

  

error_handler.js:54 EXCEPTION:./LoginComponent类中的错误LoginComponent - 内联模板:4:32导致:无法读取属性'有效'未定义的

我相信错误来自!email.vaid。但是我不明白为什么。

Item

2 个答案:

答案 0 :(得分:1)

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

您正在访问模型对象上的电子邮件属性。您的类中是否存在模型对象? 试试这段代码

  @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'
    }

答案 1 :(得分:1)

正如Karan Garg所说,看起来电子邮件是未定义的。 Angular 2的模板为您提供了一个很好的语法,用于检查是否定义了名为 safe-navigation-operator (?)的值。

*ngIf="!email?.valid"

这类似于:

*ngIf="email && !email.valid"

更多信息: https://angular.io/docs/ts/latest/guide/template-syntax.html#!#safe-navigation-operator

相关问题