Angular 9: how to focus in mat-input when key press anykey

1k views Asked by At

How to focus in mat-input when key press any key on keyboard.

have tried:

@HostListener('document:keydown', ['this.search.nativeElement.focus()'])
2

There are 2 answers

0
Yair Cohen On BEST ANSWER

Try this:

@HostListener('document:keypress', ['$event'])
    handleKeyboardEvent(event: KeyboardEvent) {
        this.search.nativeElement.focus();
    }
0
Kelvin On

YAY Fixed it and Thank you

 @HostListener('document:keypress', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) {
    this.search.nativeElement.focus();
    this.searchFocus();
  }

  keyboardFocusOut() : void {
    this.searchText = ""
    this.search.nativeElement.blur();
    this.searchFocusOut();
  }