首页 > 解决方案 > 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'从一开始就可以看到该值。这可以通过更改ngValuewith的值轻松实现object.property1。但是这种方式绑定不会像我想要的那样工作(selectedObject必须是完整的对象并且没有一个属性)。 如何在不出现此问题的情况下显示第一个属性?

标签: javascriptangulartypescriptdata-bindingdrop-down-menu

解决方案


在您的 .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>

推荐阅读