我在 Angular 5 中使用 with。我想在选择下拉值时绑定(bind)完整的 JSON 对象。所以我正面临这个问题,双向数据绑定(bind)不适用于它。当我应该编辑对象时,我在下拉列表中看不到它的类型。下面是我的代码:
HTML:
<select class="w3-input dropDown form-control" [(ngModel)]="selectedTypes" name="option" (change)="onSelectedType()">
<option *ngFor="let type of attributeTypes"
[ngValue]="type"
[selected]="selectedTypes.title === type.title ? type.title : null">
{{type.title}}</option>
</select>
TS:
this.http.get(this.localClient + "attributes?q[_id]=" + this.attributeId, { headers: this.rqstHeader })
.map(res => res.json())
.subscribe(data => {
this.attribute.title = data[0].title;
this.selectedTypes = data[0].type;
console.log(data);
});
在这里,'this.attribute.title 工作正常,因为我已将它绑定(bind)到文本框。但是“selectedTypes”在编辑模式下没有按预期工作。
如有任何帮助,我们将不胜感激。
最佳答案
在 Angular 5.x 中 *ngFor 被移除,使用 NgForOf代替 *ngFor。
TS 文件
this.ResponseFromAPI = [
{name : 'Name1', value : 'Value1'},
{name : 'Name2', value : 'Value2'},
{name : 'Name3', value : 'Value3'}
];
HTML 文件
<ng-template ngFor let-item [ngForOf]="ResponseFromAPI" let-i="index">
<option [ngValue]="item.value" >{{item.name}}</option>
</ng-template>
希望对您有所帮助。 :)
关于typescript - 两种方式的数据绑定(bind)不适用于 <select>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48186237/