I have an HTMLElement
, which is found and set in a variable that will not focus when using .focus()
. Since this is an Angular app, I have tried using nativeElement
to focus, but the element is not found.
Acceptable answers can use either method and maybe others, as long as it doesn't involve using an extra library like jQuery.
<mat-checkbox
[ngModel]="value"
[tabIndex]="tabIndex"
[id]="tabbableId"
(keydown.enter)="toggleCheckAndEmit()"
#htCheckbox
></mat-checkbox>
export class MatCheckboxWrapperComponent {
@ViewChild('htCheckbox', {static: true}) public htCheckbox?: ElementRef;
public tabbableId: string = 'tabbable-'
@Input()
public tabIndex: number = 0;
public toggleCheckAndEmit(): void {
this.value = !this.value;
this.valueChange.emit(this.value);
const checkbox = document.getElementById(this.tabbableId);
setTimeout(() => {
if (this.htCheckbox && this.htCheckbox.nativeElement) {
// this code is unreachable
this.htCheckbox.nativeElement.focus();
} else {
// this.htCheckbox.nativeElement is never found :(
}
if (checkbox) {
//mat-checkbox is always found BUT
checkbox.focus();
// document.activeElement is still <body> :(
}
}, 5000);
}
}
Seems to work for me. I implemented NgAfterViewInit
to run your method and refactored a little bit. We can access elements in template after their rendered via NgAfterViewInit (the earliest). We then reference to the element as HTMLElement, instead of ElementRef.
https://stackblitz.com/edit/angular-zzf4pd?file=src%2Fapp%2Fapp.component.ts