Angular5中Select+Option组件如何绑定复杂数据?
解决方案
很简单,在Angular里用*ngFor指令就能轻松实现这个需求,直接在app.component.html里这么写就行:
<select> <!-- 遍历tests.score里的每个子数组,拿到每个科目对应的数组项 --> <option *ngFor="let subjectEntry of tests.score" [value]="subjectEntry[0]"> {{ subjectEntry[0] }} </option> </select>
代码细节解释:
*ngFor="let subjectEntry of tests.score":循环遍历tests对象里的score数组,把每个子数组赋值给subjectEntry变量,这样就能逐个拿到每个科目的数据项。[value]="subjectEntry[0]":给每个<option>设置对应的value值,也就是子数组的第一个元素(科目名称),方便后续获取选中值。{{ subjectEntry[0] }}:在下拉框的选项中显示科目名称,和value保持一致,让用户能直观看到可选的科目。
如果你需要双向绑定选中的科目(比如要在组件里拿到用户选了哪个科目),可以先在app.component.ts里加一个变量:
export class AppComponent implements OnInit { tests = { 'name': 'Bob', 'grade': '5th', 'score': [ ['math', 'A', 'A+', 'A-'], ['english', 'B', 'B-', 'A'], ['french', 'A', 'A+', 'A'], ['chem', 'C', 'C', 'C'], ['sport', 'B', 'B', 'B'] ]}; selectedSubject: string; // 新增变量存储选中的科目 }
然后修改html里的<select>标签:
<select [(ngModel)]="selectedSubject"> <option *ngFor="let subjectEntry of tests.score" [value]="subjectEntry[0]"> {{ subjectEntry[0] }} </option> </select>
⚠️ 小提醒:使用[(ngModel)]双向绑定的话,必须在你的AppModule里导入FormsModule,否则会报错:
import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ BrowserModule, FormsModule // 一定要加上这个模块 ], // ...其他模块配置 }) export class AppModule { }
内容的提问来源于stack exchange,提问作者user9508949
相关产品推荐
相关产品推荐

