javascript - Angular:使用复杂对象时如何默认选择选择中的第一个元素
问题描述
我正在使用 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
with的值轻松实现object.property1
。但是这种方式绑定不会像我想要的那样工作(selectedObject
必须是完整的对象并且没有一个属性)。
如何在不出现此问题的情况下显示第一个属性?
解决方案
在您的 .ts 文件中:
myArray = [
{property1: "a", property2:"b"},
{property1: "c", property2:"d"},
{property1: "e", property2:"f"},
]
public selectedValue: string
public selectedObject: any
ngOnInit() {
this.selectedValue = this.myArray[0].property1
this.onValueChange();
}
onValueChange() {
const found = this.myArray.filter( obj => obj.property1 === this.selectedValue)
this.selectedObject = found? found[0] : {}
}
在你的 .html 文件中
<select [(ngModel)]="selectedValue" (ngModelChange)="onValueChange()">
<option *ngFor="let item of myArray"
[value]="item.property1">{{item.property1}}</option>
</select>
<p>selectedvalue : {{selectedValue}}</p>
<p *ngIf="selectedObject">selected object : {{selectedObject.property1}} ; {{selectedObject.property2}}</p>
推荐阅读
- javascript - 如何切换动态 div 下拉列表 NEXT.JS
- python-3.x - 如何使用 Google Chrome Headless 和 Selenium 提取 youtube 视频的评论数量?
- python - 如何按属性对列表进行排序
- python - 在加载时运行 Django celery
- jwt - 拥有 JWT 后如何获取用户的数据
- amazon-web-services - 试图找到 ssh 的私钥
- python - Python 3.8 无法导入 statsmodels.api
- python - Seaborn 线图。数据集中 1945 年之前和之后的垂直线
- javascript - 无法理解为什么类在不同的索引上被替换
- kubernetes - 为什么 calico 在 Kubernetes 中缺少一些节点对等地址?