[英]Angular: how to select by default the first element in a select when a complex object is used
I'm developing a web application using Angular 11. A component receives an array with object via input:我正在使用 Angular 11 开发 web 应用程序。组件通过输入接收带有 object 的数组:
[
{propery1: "a", property2:"b"},
{propery1: "c", property2:"d"},
{propery1: "e", property2:"f"},
]
So In my_component.ts file I have:所以在 my_component.ts 文件中我有:
@Input() myArray: any[];
private selectedObject: any; // The current object selected with all its properties!
I would like selectedObject
to be the entire object (of the array) selected via a dropdown menu.我希望selectedObject
是通过下拉菜单选择的整个 object (数组的)。 I did it like this:我是这样做的:
<select [(ngModel)]="selectedObject">
<option *ngFor="let object of myArray;" [ngValue]="object">{{object.property1}}</option>
</select>
The selectedObject
is linked with the current value object
. selectedObject
与当前值object
相关联。 I got what I wanted, but I can't understand why the dropdown appears on the screen with no options selected :我得到了我想要的,但我不明白为什么下拉菜单出现在屏幕上而没有选择任何选项:
If I open the menu, the results appear, as expected:如果我打开菜单,结果会按预期出现:
And if I select a property, the "empty property" disappears:如果我 select 一个属性,“空属性”消失:
I wish this didn't happen.我希望这没有发生。 I would like the 'a'
value to be visible right from the start.我希望从一开始就可以看到'a'
值。 This can be easily achieved by changing the value of ngValue
with object.property1
.这可以通过使用object.property1
更改ngValue
的值来轻松实现。 But this way the binding wouldn't work as I want it to ( selectedObject
must be the full object and no one property).但是这种方式绑定不会像我想要的那样工作( selectedObject
必须是完整的 object并且没有一个属性)。 How do I make the first property appear without this problem occurring?如何在不出现此问题的情况下使第一个属性出现?
In your.ts file:在你的 .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] : {}
}
In your.html file在你的.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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.