angular - 在获得角度响应后,如何在选择标签上将其余 api 调用中的值设置为 ngModel
问题描述
在我的情况下,我想默认设置从 API 响应中获取的字符串值的下拉列表,我试图在我尝试使用 ChangeDectector 的选择标签上使用 ngModel 设置该值不起作用。
组件.html
<div class="col-md-4">
<label><small>Allocated Berth</small></label>
<select class="form-control" [(ngModel)]="displayValue" (change)="onSelectBerth($event.target.value)">
<option>Select Option</option>
<option *ngFor=" let item of berthList" [value]="item.id"> {{(item.name)}}</option>
</select>
</div>
组件.ts
constructor(private berthService: BerthService,private ref: ChangeDetectorRef) { }
ngOnInit() {
this.berthService.getBerths().subscribe((response) => {
this.berthList = response;
for (let index = 0; index < this.berthList.length; index++) {
if (this.berthList[index].id === this.allocatedBerthId) {
this.displayValue = this.berthList[index].name;
console.log('Display', this.displayValue);
this.ref.detectChanges();
}
}
},(error) => {
});
}
我在 console.log 上得到 displayValue 但不在视图上
解决方案
由于选项的值是 ID <option [value]="item.id">
,传递给 ngModel 的模型也应该是 ID。所以
this.displayValue = this.berthList[index].id
应该解决这个问题
推荐阅读
- python - Python将嵌套字典转换为包含浮点元素作为单个元素的列表
- cmd - 如何在 Processbar 不可见的情况下播放 MP4
- javascript - JavaScript 过滤器在我的 NUXT 应用程序中无法正常工作
- typescript - TypeScript:还有其他方法可以检测从相似类实例化的两个对象吗?
- reactjs - vscode 在不导入模块的情况下获取 React 的代码建议
- mongodb - mongo 索引字段存在
- php - 在 Vue js 组件中使用 PhP Variavle
- r - 应用 gtsummary 包中的 tbl_summary 函数时在 R 中缓存目录错误消息
- sonarqube - SonarQube 硬编码凭证在配置文件中对安全性敏感
- php - Swagger:swagger.json 接口