无法读取Angular 2中未定义的属性“错误”?

时间:2018-07-17 06:17:32

标签: angular typescript

  

无法读取Angular 2中未定义的属性“错误”?

在使用以下代码期间,我遇到了以下代码错误,我认为我必须在FormModule中导入一些属性,例如module.ts,但我不是那是什么??请帮我解决这个问题?

Firstname: <input type="text" class="_firstname" name="txtFirstname"    [(ngModel)]="firstName" placeholder="Enter First Name"  #txtFather="ngModel"><br><br>
<div *ngIf="txtFirstname.error &&(txtFirstname.dirty || txtFirstname.touched)" class="alert alert-danger">
    <div [hidden]="!txtFirstname.errors.required">
          Name  is required!
   </div>
</div>
  

我有:

reg.component.html:8 ERROR TypeError: Cannot read property 'error' of undefined
    at Object.eval [as updateDirectives] (reg.component.html:9)
    at Object.debugUpdateDirectives [as updateDirectives] (services.ts:443)
    at checkAndUpdateView (view.ts:359)
    at callViewAction (view.ts:767)
    at execComponentViewsAction (view.ts:700)
    at checkAndUpdateView (view.ts:413)
    at callViewAction (view.ts:767)
    at execComponentViewsAction (view.ts:700)
    at checkAndUpdateView (view.ts:413)
    at callWithDebugContext (services.ts:815)

4 个答案:

答案 0 :(得分:4)

您没有名称为txtFirstname的元素。您已使用#txtFather="ngModel",所以需要使用txtFather.error而不是txtFirstname.error

您已将输入绑定到属性firstName,但是控件名称为txtFather

<input type="text" class="_firstname" name="txtFirstname" [(ngModel)]="firstName" placeholder="Enter First Name"  #txtFather="ngModel">
<br><br>
<div *ngIf="txtFather.error &&(txtFather.dirty || txtFather.touched)" class="alert alert-danger">
   <div [hidden]="!txtFather.errors.required">
          Name  is required!
   </div>
</div>

答案 1 :(得分:1)

使用?检查像这样的空值/未定义值,

txtFirstname?.error 

希望这会有所帮助!

答案 2 :(得分:1)

您需要在模块顶部声明以下内容。

import { FormsModule }   from '@angular/forms';

然后,您需要将其放在@NgModule部件的“导入”括号中

这是来自Angular Documentation的示例:

@NgModule({


imports: [
    BrowserModule,
    FormsModule
  ],
  declarations: [
    AppComponent,
    HeroFormComponent
  ],
  providers: [],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

答案 3 :(得分:0)

出现此错误是因为未定义 txtFirst 。看来您没有这样的变量。