【问题标题】:Angular: how to select by default the first element in a select when a complex object is usedAngular:使用复杂对象时如何默认选择选择中的第一个元素
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-16
      • 2021-06-20
      • 1970-01-01
      • 2020-06-07
      • 2019-06-18
      • 2021-06-27
      • 2021-03-21
      • 1970-01-01
      相关资源
      最近更新 更多