我希望在单击按钮时将焦点设置到页面顶部的
因此,如何将焦点聚焦到页面顶部的
div
。这意味着当点击按钮时进行验证,如果验证失败,则需要将焦点聚焦到页面顶部,即验证错误所在的位置。因此,如何将焦点聚焦到页面顶部的
div
呢?表单位于 modal-dialog
中。div
。这意味着当点击按钮时进行验证,如果验证失败,则需要将焦点聚焦到页面顶部,即验证错误所在的位置。div
呢?表单位于 modal-dialog
中。如果您想使一个非可聚焦元素变为可聚焦,必须向其添加 tabindex 属性,而
div
属于此类别。
更多信息请参见 tabIndex
。
使用类似以下的代码:
<div tabindex="1"></div>
甚至可以创建一个指令来帮助您自定义功能。
import { Directive, Input, ElementRef, Inject, OnChanges } from '@angular/core';
@Directive({ selector: '[focusField]' })
export class FocusDirective implements OnChanges {
@Input('focusField') focusField: any;
constructor(@Inject(ElementRef) private element: ElementRef) { }
ngOnChanges(changes){
if(changes.focusField.currentValue){
this.element.nativeElement.focus();
}
}
}
<div #myerr class="my-error">{{myError}}</div>
组件 ts:
export class YourComponent implements AfterViewInit {
@ViewChild('myerr') myErrorText: ElementRef;
ngAfterViewInit() {
this.myErrorText.nativeElement.focus();
}
}