Reputation: 2330
I had a select element that looked like this:
<select (change)="handleEvent($event)">
<option [value]="null" selected disabled>Select thing</option>
<ng-container *ngIf="data">
<ng-container *ngFor="let item of data">
<option [value]="item.id">{{ item.name }}</option>
</ng-container>
</ng-container>
</select>
Note that the default option did not come from the dynamic data and I disabled it from being selected. I wanted to access the entire data object rather than just the id when an option was selected so I did this:
<select [(ngModel)]="selectedItem" (change)="handleItemSelected()">
<option [value]="null" selected disabled>Select thing</option>
<ng-container *ngIf="data">
<ng-container *ngFor="let item of data">
<option [ngValue]="item">{{ item.name }}</option>
</ng-container>
</ng-container>
</select>
This worked except the disabled default option no longer showed up until I opened the select box. I did some reading and learned that this is because the default select option becomes whatever the value of
selectedItem
is when the component initializes which in this case was undefined. However, adding
this.selectedItem = {
name: "Select a thing"
}
did not populate the field either. I tried it both on init and in the constructor. Does anyone know:
1: why the default option is not populating
2: how to make the the default option disabled while still using ngModel
Upvotes: 0
Views: 1758
Reputation: 1612
Define selectedItem as null since the option has value null
selectedItem = null;
Upvotes: 1