首页 > 解决方案 > 在获得角度响应后,如何在选择标签上将其余 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 但不在视图上

标签: angular

解决方案


由于选项的值是 ID <option [value]="item.id">,传递给 ngModel 的模型也应该是 ID。所以

this.displayValue = this.berthList[index].id

应该解决这个问题


推荐阅读