DEV Community

Dhanush
Dhanush

Posted on

Angular MatSelect Input AutoFocus on Button click

The Select options panel can be controlled by adding a template variable then calling the methods programmatically.

Eg:

<button (click)="mySelect.open()">Open</button>
<button (click)="mySelect.toggle()">Toggle</button>
<button (click)="mySelect.close()">Close</button>

  <mat-form-field>
    <mat-label>Select Color</mat-label>
    <mat-select #mySelect [(value)]="selected">
      <mat-option value="yellow">Yellow</mat-option>
      <mat-option value="black">Black</mat-option>
      <mat-option value="red">Red</mat-option>
    </mat-select>
  </mat-form-field>
Enter fullscreen mode Exit fullscreen mode

Image description

To get an instance of mat-select inside the component class, import the MatSelect class and get mat-select instance using @ViewChild as shown below:

// app.component.ts
import { Component, ViewChild } from '@angular/core';
import { MatSelect } from '@angular/material/select';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'angular-mat-select-app';

  @ViewChild('mySelect') mySelect: MatSelect;

  selected: string;

  OpenSel() {
    this.mySelect.open()
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)