我有一個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);
}
}
uj5u.com熱心網友回復:
似乎對我有用。我實作NgAfterViewInit了運行您的方法并進行了一些重構。我們可以在模板中通過 NgAfterViewInit(最早的)渲染后訪問元素。然后我們將元素參考為 HTMLElement,而不是 ElementRef。
https://stackblitz.com/edit/angular-zzf4pd?file=src/app/app.component.ts
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/421062.html
標籤:
