Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度验证。未定义错误_Javascript_Html_Angular_Validation - Fatal编程技术网

Javascript 角度验证。未定义错误

Javascript 角度验证。未定义错误,javascript,html,angular,validation,Javascript,Html,Angular,Validation,我正在尝试使用模板驱动的表单,但我似乎无法使errors属性按照教程正确工作以验证minlength。我在开发工具的页面加载中遇到的错误是: ContactFormComponent.html:8错误类型错误:无法读取属性 null的“minlength” 所以问题是ngModel上没有.error属性。我不确定我是否误解了某些内容或错误地设置了表单。没有验证,一切都按预期进行 HTML 模块 import { NgModule } from '@angular/core'; impo

我正在尝试使用模板驱动的表单,但我似乎无法使errors属性按照教程正确工作以验证minlength。我在开发工具的页面加载中遇到的错误是:

ContactFormComponent.html:8错误类型错误:无法读取属性 null的“minlength”

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

HTML

模块

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 { }

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

email.errors上的
*ngIf
会阻止对子html元素进行求值,从而阻止错误的发生

根据虚幻评论,您也不能通过执行
来同时使用
*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>

电子邮件太短了

你为什么不干脆
?@theirreal是的,这很有效,谢谢。让我走上了正确的道路,缩小了我在代码的另一部分中错误使用*ngIf的范围。谢谢
<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>