typescript - 两种方式的数据绑定(bind)不适用于 <select>

标签 typescript angular5

我在 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/

相关文章:

javascript - 对于不相关的模型字段, Angular react 形式抛出 "Cannot find control with name"

javascript - 澄清 Typescript 的目标和库设置的功能

typescript - 键入一个将任何参数包装到数组中的函数

angular - Ngif 用于空字符串验证 Angular 5

Angular 5 - 当通过 @Input 将函数从组件传递到指令时, "this"指的是指令而不是组件

Angular ngx-bootstrap 崩溃不是动画

reactjs - 将 React 17 更新为 React 18 - Typescript - ReactNode 类型的子代不再处理 `void` 的内联条件渲染

javascript - 将工厂注入(inject) Controller AngularJS + TypeScript

datetime - Angular 5 ng-pick-datetime 日期格式

angular - 使用 Angular 2+ 在 JSON 文件中按 ID 搜索对象