【发布时间】:2021-11-16 15:47:04
【问题描述】:
我正在使用 Angular 11 开发 Web 应用程序。组件通过输入接收带有对象的数组:
[
{propery1: "a", property2:"b"},
{propery1: "c", property2:"d"},
{propery1: "e", property2:"f"},
]
所以在 my_component.ts 文件中我有:
@Input() myArray: any[];
private selectedObject: any; // The current object selected with all its properties!
我希望selectedObject 成为通过下拉菜单选择的整个(数组的)对象。我是这样做的:
<select [(ngModel)]="selectedObject">
<option *ngFor="let object of myArray;" [ngValue]="object">{{object.property1}}</option>
</select>
selectedObject 与当前值 object 相关联。我得到了我想要的,但是我不明白为什么下拉菜单出现在屏幕上而没有选择任何选项:
如果我打开菜单,结果会按预期出现:
如果我选择一个属性,“空属性”就会消失:
我希望这不会发生。我希望从一开始就可以看到 'a' 值。这可以通过将ngValue 的值更改为object.property1 来轻松实现。但是这种方式绑定不会像我想要的那样工作(selectedObject 必须是 full object 并且没有一个属性)。
如何在不出现此问题的情况下显示第一个属性?
【问题讨论】:
标签: javascript angular typescript data-binding drop-down-menu