DEV Community

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

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

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.

Top comments (0)