I'm developing a web application using Angular 11. A component receives an array with object via input:
[
{propery1: "a", property2:"b"},
{propery1: "c", property2:"d"},
{propery1: "e", property2:"f"},
]
So In my_component.ts file I have:
@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. 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. 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:
I wish this didn't happen. I would like the 'a' value to be visible right from the start. This can be easily achieved by changing the value of ngValue with object.property1. But this way the binding wouldn't work as I want it to (selectedObject must be the full object and no one property).
How do I make the first property appear without this problem occurring?
In your .ts file :
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 you .html file
<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>