简体   繁体   中英

ngModel in Angular Form

I'm trying to access to data form my form in the TS file. I got error : RROR TypeError: Cannot read property 'name' of undefined

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.

<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.

The solution is that you shouldn't make the data null ever. And initialize the data as

 data = {} as employee;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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