I am brand new to Angular and I have been working on creating a custom Component. Specifically, I am trying to display a list of Courses (objects) which consist of two properties: id and name. So far, this logic is functioning properly. However, when attempting to add a new Course to the existing array of Courses in my custom-component.html using ngModel for binding, an error is occurring with the following message:
ERROR TypeError: Cannot read property 'name' of undefined.
Below is the code that I am currently working with:
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 { }