'Found HTMLElement with tabindex will not focus()

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);
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source