title: How to debug "TypeError: Cannot read property 'name' of undefined" with Angular 4 data binding?
body: <p>I am new to Angular and I am writing a custom Component as mentioned below. I am displaying a list of Course(object) that has 2 properties, id and name. This logic works fine. However when I am writing a logic to add new Course in the existing array of Course in custom-component.html using ngModel for binding, I am getting following error:</p>
  
  <blockquote>
    <p>ERROR TypeError: Cannot read property 'name' of undefined.</p>
  </blockquote>
  
  <p>My code is given below:</p>
  
  <p>custom-component.component.html</p>
  
  <pre><code>&lt;h2&gt;{{ title }}&lt;/h2&gt;
  &lt;ul class="courses"&gt;
    &lt;li *ngFor="let course of courses" (click)="onSelect(course)"
    [class.selected]="course===selectedCourse"&gt;
        &lt;span class="badge"&gt;{{course.id}}&lt;/span&gt; {{course.name}}
    &lt;/li&gt;
  &lt;/ul&gt;
  &lt;div *ngIf="selectedCourse"&gt;
    &lt;ul class="courses"&gt;&lt;li&gt;
    &lt;span class="badge"&gt;{{selectedCourse.id}}&lt;/span&gt; {{selectedCourse.name}}&lt;/li&gt;
  &lt;/ul&gt;
  &lt;/div&gt;
  &lt;div&gt;
  &lt;span&gt;Enter name: &lt;/span&gt;&lt;input type="text" name="name" [(ngModel)]="course.name"&gt;
  &lt;span&gt;Enter id:&lt;/span&gt;&lt;input type="text" name="id" [(ngModel)]="course.id"&gt;
  &lt;button (click)="addCourse(course)"&gt;Add Course&lt;/button&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>custom-component.component.ts</p>
  
  <pre><code>import { Course } from './../Course';
  import { Component, OnInit } from '@angular/core';
  import { CoursesService } from '../courses.service';
  
  @Component({
    selector: 'app-custom-component',
    templateUrl: './custom-component.component.html',
    styleUrls: ['./custom-component.component.css']
  })
  export class CustomComponent implements OnInit {
    title = "Choosen Courses";
    selectedCourse: Course;
    courses: Course[];
    constructor(service: CoursesService) {
      this.courses = service.getCourse();
     }
  
    ngOnInit() {
    }
    onSelect(course: Course):void{
      this.selectedCourse=course;
    }
    addCourse(course: Course):void{
      this.courses.push(course);
    }
  }
  </code></pre>
  
  <p>app.module.ts</p>
  
  <pre><code>import { BrowserModule } from '@angular/platform-browser';
  import { NgModule } from '@angular/core';
  import { FormsModule } from '@angular/forms';
  
  import { AppComponent } from './app.component';
  import { CustomComponent } from './custom-component/custom-component.component';
  import { CoursesService } from './courses.service';
  
  
  @NgModule({
    declarations: [
      AppComponent,
      CustomComponent
    ],
    imports: [
      BrowserModule,
      FormsModule
    ],
    providers: [
      CoursesService
    ],
    bootstrap: [AppComponent]
  })
  export class AppModule { }
  </code></pre>