Search code examples
angularangular7angular-servicesangular-ngmodelangular-forms

TypeError: Cannot read property '_id' of undefined angular7


I have a component employee I am trying to create a form, for which I have created "employee component", "employee service" and "employee model"

In employee.component.html I have below form

 <form #employeeform="ngForm" (ngSubmit)="onSubmit(employeeform)">
          <input type="hidden" name="_id"  [(ngModel)]="employeeservice.selectedEmployee._id" #_id="ngModel"/>
        </form>

In employee.component.ts I have below code

 import { Component, OnInit } from '@angular/core';
 import { EmployeeService } from '../shared/employee.service';

 @Component({
    selector: 'app-employee',
    templateUrl: './employee.component.html',
    styleUrls: ['./employee.component.css'],
    providers : [EmployeeService]
 });

 export class EmployeeComponent implements OnInit {
    constructor(private employeeservice : EmployeeService) { }
      ngOnInit() {
      }
   }

This is my employee.service.ts file which I have imported in employee component

 import { Injectable } from '@angular/core';
 import { HttpClient } from '@angular/common/http';
 import { Observable } from 'rxjs';
 import { Employee } from './employee.model';

 @Injectable({
   providedIn: 'root'
 })
 export class EmployeeService {
   selectedEmployee : Employee;
   employees: Employee[];

   constructor() { }
 }

Here is my employee.model.ts which I have imported in employee service

 export class Employee {
     _id: string;
     name: string;
     position : string;
     office : string;
     salary : number;
 }

I am getting the below error in my browser console when I run the command "ng serve"

 EmployeeComponent.html:9 ERROR TypeError: Cannot read property '_id' of undefined
at Object.eval [as updateDirectives] (EmployeeComponent.html:9)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:23911)
at checkAndUpdateView (core.js:23307)
at callViewAction (core.js:23548)
at execComponentViewsAction (core.js:23490)
at checkAndUpdateView (core.js:23313)
at callViewAction (core.js:23548)
at execComponentViewsAction (core.js:23490)
at checkAndUpdateView (core.js:23313)

Am I missing any imports that a form needs or what could be the error. I am a beginner and trying to learn angular. I have googled for the solution, but I couldn't find any relevant solution. Please help me out


Solution

  • It is as the error says: you want to access the _id but the selectedEmployee is never actually defined.

    You can either only display the element when it has been defined using *ngIf on your html element or give it a default value like so selectedEmployee : Employee = {} (setting any variable needed from the class accordingly)