How to set focus on angular material autcomplete input field
Adrian Matei
Posted on January 31, 2022
Project Codever
- get access to the input field via template variable
@ViewChild('publicSearchBox') searchBoxField: ElementRef;
- get access to the autcomplete trigger to close the panel (we don't want that when the page loads) -
@ViewChild(MatAutocompleteTrigger) autocompleteTrigger: MatAutocompleteTrigger;
- call
focus()
andclosePanel()
on the two elements in one of Angular's lifecycle hooks - here inAfterViewInit
:
@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();
}
}
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)"
>
Shared with ❤️ from Codever. Use 👉 copy to mine functionality to add it to your personal snippets collection.
💖 💪 🙅 🚩
Adrian Matei
Posted on January 31, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.