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:
ERROR TypeError: Cannot read property 'name' of undefined.
My code is given below:
custom-component.component.html
<h2>{{ title }}</h2>
<ul class="courses">
<li *ngFor="let course of courses" (click)="onSelect(course)"
[class.selected]="course===selectedCourse">
<span class="badge">{{course.id}}</span> {{course.name}}
</li>
</ul>
<div *ngIf="selectedCourse">
<ul class="courses"><li>
<span class="badge">{{selectedCourse.id}}</span> {{selectedCourse.name}}</li>
</ul>
</div>
<div>
<span>Enter name: </span><input type="text" name="name" [(ngModel)]="course.name">
<span>Enter id:</span><input type="text" name="id" [(ngModel)]="course.id">
<button (click)="addCourse(course)">Add Course</button>
</div>
custom-component.component.ts
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);
}
}
app.module.ts
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 { }