简体   繁体   English

角度形式的 ngModel

[英]ngModel in Angular Form

I'm trying to access to data form my form in the TS file.我正在尝试从 TS 文件中的表单访问数据。 I got error : RROR TypeError: Cannot read property 'name' of undefined我收到错误:RROR TypeError:无法读取未定义的属性“名称”

My code is like this:我的代码是这样的:

 import { Component, OnInit } from '@angular/core'; import { employee } from '../models/Employee'; import { NgForm } from '@angular/forms'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; @Component({ selector: 'app-employee-form', templateUrl: './employee-form.component.html', styleUrls: ['./employee-form.component.css'] }) export class EmployeeFormComponent implements OnInit {\\ data: employee; constructor() { } ngOnInit() { } onSubmit(form:NgForm ) { alert("Hello " + JSON.stringify(this.data)); } }
 <div class="container"> <form #form="ngForm" (ngSubmit)="onSubmit(form)"> <div class="form-group"> <label for="form">name</label> <input type="text" class="form-control" id="name" [(ngModel)]="data.name" required> </div> </div> <button type="submit" class="btn btn-success" >Submit</button> </form> </div>

I didnt find my mistake, any idea?我没有发现我的错误,知道吗?

thanks谢谢

Do the template binding with a safe navigation operator.使用安全导航操作符进行模板绑定。 This way, if "data" is not defined, your code will not try to read prop name from it.这样,如果未定义“数据”,您的代码将不会尝试从中读取道具name

<input type="text" class="form-control" id="name"  [(ngModel)]="data?.name" required>

In case, if the prop data is undefined and you want to use data as a container to store the form values then you have to at least create an empty object, for example, initialize data as data = {} It will create keys on the fly.如果 prop data未定义,并且您想使用data作为容器来存储表单值,那么您至少必须创建一个空对象,例如,将数据初始化为data = {}它将在飞。

The solution is that you shouldn't make the data null ever.解决方案是您永远不应该使数据为空。 And initialize the data as并将数据初始化为

 data = {} as employee;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM