DEV Community

Cover image for How to set focus on angular material autcomplete input field
Adrian Matei for Codever

Posted on • Edited on • Originally published at codever.dev

3 2

How to set focus on angular material autcomplete input field

Project Codever

  1. get access to the input field via template variable @ViewChild('publicSearchBox') searchBoxField: ElementRef;
  2. get access to the autcomplete trigger to close the panel (we don't want that when the page loads) - @ViewChild(MatAutocompleteTrigger) autocompleteTrigger: MatAutocompleteTrigger;
  3. call focus() and closePanel() on the two elements in one of Angular's lifecycle hooks - here in AfterViewInit :
@Component({
  selector: 'app-searchbar',
  templateUrl: './searchbar.component.html',
  styleUrls: ['./searchbar.component.scss']
})
export class SearchbarComponent implements OnInit, AfterViewInit {

  @ViewChild('publicSearchBox') searchBoxField: ElementRef;
  @ViewChild(MatAutocompleteTrigger) autocompleteTrigger: MatAutocompleteTrigger;

  ngAfterViewInit(): void {
    this.searchBoxField.nativeElement.focus();
    this.autocompleteTrigger.closePanel();
  }

}
Enter fullscreen mode Exit fullscreen mode

Below you can see how the referenced template variable (publicSearchBox) and the angular autocomplete trigger are defined in the angular html template:

  <input
    #publicSearchBox
    #autocompleteTrigger="matAutocompleteTrigger"
    matInput
    type="text"
    class="form-control"
    [formControl]="searchControl"
    placeholder="{{getPlaceholderTextForSearchbar()}}"
    [matAutocomplete]="auto"
    (focus)="focusOnSearchControl()"
    (focusout)="unFocusOnSearchControl()"
    [class.my-snippets-selection]="searchDomain === 'my-snippets'"
    [class.my-bookmarks-selection]="searchDomain === 'my-bookmarks'"
    [class.public-snippets-selection]="searchDomain === 'public-snippets'"
    (keyup)="watchForTags(publicSearchBox.value)"
    (keyup.enter)="$event.target.blur(); autocompleteTrigger.closePanel();searchBookmarksFromSearchBox(publicSearchBox.value)"
  >
Enter fullscreen mode Exit fullscreen mode

Shared with ❤️ from Codever. Use 👉 copy to mine functionality to add it to your personal snippets collection.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more