繁体   English   中英

发现带有 tabindex 的 HTMLElement 将不会聚焦()

[英]Found HTMLElement with tabindex will not focus()

我有一个HTMLElement ,它在使用.focus()时不会聚焦的变量中找到并设置。 由于这是一个 Angular 应用程序,我尝试使用nativeElement进行对焦,但找不到该元素。

可接受的答案可以使用任何一种方法,也可以使用其他方法,只要它不涉及使用像 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);
    }
}

似乎对我有用。 我实现NgAfterViewInit来运行您的方法并进行了一些重构。 我们可以在模板中通过 NgAfterViewInit(最早的)渲染后访问元素。 然后我们将元素引用为 HTMLElement,而不是 ElementRef。

https://stackblitz.com/edit/angular-zzf4pd?file=src%2Fapp%2Fapp.component.ts

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM