I have option selection box in HTML. I already managed how to send the selected items (in my example id of the course) to the array, from that box. Is saves to courseDataSend like ['1'] or ['1','2']. I can console.log() it.
But now I need to create an object sendCourse with property id_course and that id_course should be taken from from courseDataSend array, so I tried to pass it through like:
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]
}
}
reg() happens after button click submit. But then this error appears in console:
TypeError: Cannot set property 'id_course' of undefined
The For loop is there because I want to create the object once, send it to the server, and then if there is another option selected from the box - the object is replaced by the new data and then again sent to the backend server.
I don't know what do do.
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]
}
}
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: hold 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>