Angular 无法保存数组';对象值问题的第一个值
我有HTML中的选项选择框。我已经设法将所选项目(在本课程的示例id中)从该框发送到数组。保存到Angular 无法保存数组';对象值问题的第一个值,angular,typescript,Angular,Typescript,我有HTML中的选项选择框。我已经设法将所选项目(在本课程的示例id中)从该框发送到数组。保存到coursedasasend中,如['1']或['1','2']。我可以console.log()it 但是现在我需要创建一个属性为id\u-course的对象sendCourse,并且该id\u-course应该从courseDataSend数组中获取,所以我尝试通过如下方式传递它: reg() { for(let i=0; i<this.courseDataToSend.leng
coursedasasend
中,如['1']
或['1','2']
。我可以console.log()
it
但是现在我需要创建一个属性为id\u-course
的对象sendCourse
,并且该id\u-course
应该从courseDataSend
数组中获取,所以我尝试通过如下方式传递它:
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>
选择您的课程(其他):
{{course.name}
要选择更多:按住控制按钮并
点击
登记
问题是由于在定义变量之前试图设置对象值。您需要设置整个对象:
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], id_user: undefined }
}
正在工作的stackblitz示例显示了未定义和空值如何传播,并且可以针对每种情况进行处理:
问题是由于在定义变量之前试图设置对象值。您需要设置整个对象:
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], id_user: undefined }
}
正在工作的stackblitz示例显示了未定义和空值如何传播,并且可以针对每种情况进行处理:
只需更改sendCourse变量声明,如下所示
sendCourse : any = {
'id_user': '',
'id_course': ''
}
只需更改sendCourse变量声明,如下所示
sendCourse : any = {
'id_user': '',
'id_course': ''
}
. JSON是一种文本格式,如CSV或XML。。JSON是一种文本格式,如CSV或XML。谢谢。非常好,谢谢。工作得很好。