angularangular-materialfocusmat-selectmat-option

Issue with Angular Mat Select showing keyboard focus and mouseover focus


Posting this here to save someone else the headache.

Angular automatically focuses on the first available option when no initial value is set. This can be confusing to the user, because it shows focus on the first option as well as focusing options that are hovered (two focused options at the same time). After researching online there are a ton of bloated and non-accessible answers to this dilemma.


Solution

  • I found that you can show focus on hover AND keep keyboard focus/controls, by adding a hidden option with style="display:hidden" and setting that as the default value of your Mat Select.

    Now all of the options are unselected initially and will only show focus on options that are hovered. If the user tabs or uses keyboard controls the focus stays within the Mat Select and is just as keyboard accessible.

    Hope this helps someone out there that's having the same issue!

    //HTMl
          <mat-form-field>
            <mat-label>Select</mat-label>
            <mat-select #mySelect value="initialSelection">
              <mat-option value ="empty" style="display: none;"></mat-option>
              <mat-option *ngFor="let selection of selections" [value]="selection.selectionId"> 
                {{ selection.selectionId }}
              </mat-option>
            </mat-select>
          </mat-form-field>
    
    //TS
    
      public initialSelection = 'empty';