Reputation: 2552
I'm having big problems on SAFARI with basic html SELECT component.
This is the code:
idFamily:any = null;
listProductFamily: ProductFamily[];
this.productFamilyService.GetAll().subscribe(
data => {
this.listProductFamily = data;
},
error => {
this.errorMessage = <any>error;
}
);
<select class="form-control" [(ngModel)]="idFamily" [ngModelOptions]="{standalone: true}">
<option *ngFor="let f of listProductFamily" [value]="f.idFamily">{{f.code}} - {{f.family}}</option>
</select>
The problem is this:
On SAFARI when the select is loaded, it is set on the first value of the option list.
On Chrome, IE, FF the select is set on NULL value (empty)
On Safari, even if the select is set on a value actually the idFamily variable where it is binded has not value... idFamily gets a value only if the user select a value... thats it.
I don't know how to solve this problem...
Hope its clear Thanks to support
Upvotes: 4
Views: 2255
Reputation: 108
I've run into this same issue where Safari will select the first item in a <select>
when the ngModel property doesn't match because it is in an 'empty' state and there's no matching item in the array. My workaround was to add a matching empty <option>
. In your case, I think this will work:
<select class="form-control" [(ngModel)]="idFamily">
<option [value]="null"></option>
<option *ngFor="let f of listProductFamily" [value]="f.idFamily">{{f.code}} - {{f.family}}</option>
</select>
In our case, we use uuids for model ids, so we use empty string for initial values. Component:
export class SomeComponent {
id = '';
}
template:
<select [(ngModel)]="id">
<option value=""></option>
<option *ngFor="let item of items" [value]="item.id">{{ item.name }}</option>
</select>
In either case, Safari should select the empty option on initial load.
Upvotes: 4
Reputation: 61
I've resolved a similar issue by using reactive forms and the AfterViewInit
lifecycle hook.
Doing the following will set child form values to null
, effectively clearing the defaults that Safari has set:
ngAfterViewInit() {
this.exampleFormName.reset();
}
Note: this.exampleFormName
is of type FormGroup
I am also using *ngFor
to load option values dynamically and reset()
doesn't interfere with it!
Upvotes: 1
Reputation: 27303
Remove Standalone
<select class="form-control" [(ngModel)]="idFamily">
<option *ngFor="let f of listProductFamily" [ngValue]="f.idFamily">{{f.code}} - {{f.family}}</option>
</select>
standalone: Defaults to false. If this is set to true, the ngModel will not register itself with its parent form, and will act as if it's not in the form. This can be handy if you have form meta-controls, a.k.a. form elements nested in the tag that control the display of the form, but don't contain form data.
Check AngularDoc For MoreInfo:https://angular.io/api/forms/NgModel#options
Upvotes: 1