角度验证.error未定义

时间:2017-07-08 18:16:42

标签: javascript html5 angular validation

我正在尝试使用模板驱动的表单,我似乎无法根据教程Here正确地使用errors属性来验证minlength。我在开发工具中加载页面的错误是:

  

ContactFormComponent.html:8 ERROR TypeError:无法读取属性   'minlength'为null

所以问题是ngModel上没有.error属性。我不确定我是否误解了某些内容或错误地设置了表单。没有验证,一切都按预期工作。

HTML

<form (ngSubmit)="onSubmit()" #contactForm="ngForm">
    <div class="form-group">
        <label for="email">Email</label>
        <input minlength="6" maxlength="50" name="email" class="form-control" id="email" placeholder="Email" required email [(ngModel)]="contactForm.email" #email="ngModel">
        <div *ngIf="email.dirty || email.touched" class="alert alert-danger">
            <div [hidden]="!email.errors.minlength">
                <span>Email is too short</span>
            </div>
        </div>
    </div>
</form>

组件

import { Component, Input } from '@angular/core';
import { Contact } from './contact';
import { AppService } from '../app.service';

@Component({
  selector: 'selected-page',
  template: require('./contact-form.html'),
  providers: [AppService]
})

export class ContactFormComponent {
    contactForm = new Contact();
    submitted: boolean = false;

    constructor (private appService: AppService) {}

    onSubmit() {
        this.appService.emailContact(contactForm).then(data => {
            this.submitted = true;
        });
    }
}

模块

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes }   from '@angular/router';
import { FormsModule } from '@angular/forms';

import { AppComponent }  from './app.component';
import { ContactFormComponent } from './contact/contact-form.component';
import { HttpModule } from '@angular/http';
import { AppService } from './app.service';

const appRoutes: Routes = [
    {
        path: 'contact',
        component: ContactFormComponent
    }
]

@NgModule({
    imports: [
        BrowserModule,
        RouterModule.forRoot(appRoutes),
        FormsModule,
        HttpModule
    ],
    declarations: [ 
        AppComponent,
        ContactFormComponent,
    ],
    bootstrap: [ AppComponent ],
    providers: [ AppService ]
})

export class AppModule { }

1 个答案:

答案 0 :(得分:0)

问题是我在我的代码中错误地使用*ngIf并假设它是如何工作的。我更新了我的原始帖子,以正确反映这一点。

*ngIf上的email.errors会停止评估子html元素,从而阻止错误发生。

根据TheUnreals评论,您也不能通过*ngIf一起使用!email.errors?.minlength

我有什么

<div *ngIf="email.dirty || email.touched" class="alert alert-danger">
    <div [hidden]="!email.errors.minlength">
        <span>Email is too short</span>
    </div>
</div>

正确答案

<div *ngIf="email.errors && (email.dirty || email.touched)" class="alert alert-danger">
    <div [hidden]="!email.errors.minlength">
        <span>Email is too short</span>
    </div>
</div>