Angular Material 2 browser autofill for mat-select not working

南楼画角 提交于 2019-12-06 02:23:37

问题


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.


回答1:


If you want auto-complete use mat-autocomplete and not mat-select Here's a sample

<mat-form-field>
  <input type="text" placeholder="Address" matInput [(ngModel)]="state"
  [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let s of states" [value]="s"> {{s}} </mat-option>
    </mat-autocomplete>
</mat-form-field>

Here's a stackblitz demo




回答2:


Because mat-select doesn't use a real select under the hood.

The only workaround is creating an input with the same name property to catch autofill value from the browser and feed it to mat-select.

This input can't be hidden or display:none. Use postition: absolute with z-index: -1 or right: 1000% to "hide" it.




回答3:


Please add following attribute in your input tag like

autocomplete="name"
autocomplete="email"
autocomplete="tel" 

etc.... in your html code.

Please refer this document for more details:

https://developers.google.com/web/updates/2015/06/checkout-faster-with-autofill

This document will help you to fix the issue.



来源:https://stackoverflow.com/questions/47725599/angular-material-2-browser-autofill-for-mat-select-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!