I have a dropdown in an Angular 2 project:
<div class="form-group">
<label for="vendors">Vendors</label>
<select class="form-control" id="vendor_id" name="vendor_id" [(ngModel)]="selectedVendor" (ngModelChange)="onVendorChange($event)" required>
<option *ngFor=" let vendor of vendors " [ngValue]="vendor"> {{vendor.business_name}} </option>
</select>
</div>
This works fine in Chrome, but when I open it in Safari, when the page is loaded it shows the first item as selected even if I didn't selected anything. However, if I click "Submit" it will show "This field is mandatory".
In Safari it shows the first item as selected, but actually it's not selected. How to fix this?
In fact, you may find that the accepted answer is insufficient. At least using Angular 5 and Safari, I have found that you must explicitly make the option undefined. In other words:
<option disabled selected value=undefined> --Select-- </option>
Otherwise, the option will simply be marked as disabled and Safari will continue to show that it has the first real option selected, when in fact it isn't (and can't be).
This is not an angular issue, this is the default behavior on safari/mobile safari. An easy solution/workaround is shown below.
If you add another option box such as:
<option disabled selected value> --Select-- </option>
Then your code becomes:
<div class="form-group">
<label for="vendors">Vendors</label>
<select class="form-control" id="vendor_id" name="vendor_id" [(ngModel)]="selectedVendor" (ngModelChange)="onVendorChange($event)" required>
<option disabled selected value> --Select-- </option>
<option *ngFor=" let vendor of vendors " [ngValue]="vendor"> {{vendor.business_name}} </option>
</select>
</div>
This way you cannot re-select the first "Select" box after the user has made a valid selection, answer taken from this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With