Set focus on input field with autocomplete in angular

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
  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 {


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

    []="searchDomain === 'my-snippets'"
    []="searchDomain === 'my-bookmarks'"
    [class.public-snippets-selection]="searchDomain === 'public-snippets'"
    (keyup.enter)="$; autocompleteTrigger.closePanel();searchBookmarksFromSearchBox(publicSearchBox.value)"

Shared with from 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Subscribe to our newsletter for more code resources and news

Adrian Matei

Adrian Matei
Life force expressing itself as a coding capable human being

Default value for jax-rs query parameter

Default value for jax-rs query parameter code snippet Continue reading

Unmarshalling xml string to java object with JAXB

Published on February 20, 2022

Execute delete statement with jpa query

Published on February 19, 2022