I have a form that represents an address and I'm using mat-select for the state/province. Unfortunately it's not autofilling the state/province (I'm assuming because it's not a native select). Here is my markup:
<mat-form-field>
<mat-select placeholder="State"
[(ngModel)]="state"
autocomplete="billing address-level1">
<mat-option *ngFor="let s of states" [value]="s.abbreviation">{{ s.name }}</mat-option>
</mat-select>
</mat-form-field>
I'm not sure if I'm missing something or if the browsers autofill isn't working because mat-select isn't a native control. Anyone have any idea how to make autofill work in this scenario? The only thing I can think of is creating a native select, binding it to the same model field and setting it's style to display: none
.
Answers 1 : of How to clear mat- autocomplete when no option is selected from autocomplete dropdown. You can remove the formControl-binding from your input and when you select an option you set that id to your form.
Just for information, you need to make sure the datatype of the default value matches with that of the options, for.eg, <mat-select [(value)]="heroes[0]. id"> <mat-option *ngFor="let hero of heroes" [value]="hero.id">{{ hero.name }}</mat-option> </mat-select> will work.
To add options to the select, add <mat-option> elements to the <mat-select> . Each <mat-option> has a value property that can be used to set the value that will be selected if the user chooses this option. The content of the <mat-option> is what will be shown to the user.
We can use NgModel to get and set values in Select option for Angular Material Select as well as native Select. Suppose we have component property. selectedGame = "Football"; Use ngModel with <mat-select> to set and get value as following.
The material/angular-material does not support browser autofill by default for the mat-select.
mat-select is not the standard type of input it will not work with autofill.
The issue has already opened https://github.com/angular/components/issues/19083 We' are waiting for the official solution.
Meanwhile, I customized and fixed the issue, please verify the below working example
Visually hidden input
<input class="hide-text-for-autofill" type="text" name="country" [formControl]="autoFillCountry">
.hide-text-for-autofill { position: absolute; z-index: -1; right: 1000%; }
Update the hidden input value to mat select
autoFillCountry = new FormControl();
................
................
................
this.autoFillCountry.valueChanges.subscribe((selectedValue) => {
this.formGroup.controls.country.setValue(selectedValue);
});
stackblitz URL:
https://stackblitz.com/edit/mat-select-angular-material-autofill
I have tested in chrome and edge browsers, It's working as expected
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