I have a selection box in HTML where users can select options. I've figured out how to store the selected items (in this case, the course ID) in an array called courseDataSend
, such as ['1']
or ['1','2']
. I can use console.log()
to display it.
Now, I need to create an object named sendCourse
with a property called id_course
that should take the values from the courseDataSend
array. I tried to achieve this using the following code:
reg()
{
for(let i=0; i<this.courseDataToSend.length; i++)
{
console.log(this.courseDataToSend[i]) // It displays '1' or '1' and then '2' when options are selected
this.sendCourse.id_course=this.courseDataToSend[i]
}
}
The reg()
function is triggered upon clicking the submit button. However, an error message appears in the console stating:
TypeError: Cannot set property 'id_course' of undefined
I included the For loop because I want to create the object once, send it to the server, replace it with new data if another option is selected, and then resend it to the server.
I'm not sure what to do next.
file: register.component.ts
coursesData : any = {}
courseDataToSend : Array<string> = []
sendCourse : {
'id_user': any,
'id_course': any,
}
constructor(
private _auth: AuthService,
private _courseService: CourseService,
private _router: Router,
private _flashMessage: FlashMessagesService) { }
ngOnInit() {
this._courseService.getCourses()
.subscribe(
res =>
{
this.coursesData= res['courses'];
console.log(this.coursesData)
}
)
}
reg()
{
for(let i=0; i<this.courseDataToSend.length; i++)
{
console.log(this.courseDataToSend[i]) // It shows '1' or '1' and then '2' when options selected
this.sendCourse.id_course=this.courseDataToSend[i]
}
}
file: register.component.html:
<div class="form-group">
<label for="registerCourses">Select your courses (additional):</label>
<select [(ngModel)]="courseDataToSend" name="courses" multiple class="form-control"
id="exampleFormControlSelect2">
<option *ngFor="let course of coursesData" [value]="course.id">{{course.name}}</option>
</select>
<small id="interestsHelp" class="form-text text-muted">To select more than one item: hold down the control button and click</small>
</div>
<div class="text-right">
<button (click)="reg()" type="submit" class="btn btn-primary"
style="margin: 15px;">Register</button>
</div>