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.
Top comments (1)
Focusing Material autocomplete inputs can definitely be trickier than it first appears.
Itβs interesting how even small focus behaviours like this can have wider UX and accessibility implications once applications scale.
Thanks for sharing