我想在点击按钮时将焦点设置到页面顶部的div。这意味着它在单击按钮时进行验证,如果验证失败,则需要将焦点集中在页面顶部,验证错误显示在该处。
那么如何将焦点放在页面div的顶部。形式是模态对话。
答案 0 :(得分:1)
如果你想让一个不可聚焦的元素可聚焦,你必须添加一个 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();
}
}
}
答案 1 :(得分:0)
尝试类似的东西
<强> component.html 强>
<div #topElement> </div>
<button (click)="changeFocus()"> change Focus </button>
<强> component.ts 强>
export default class MyComponent {
changeFocus() {
window.location.hash = '#topElement';
}
}
答案 2 :(得分:0)
您可以尝试在组件中添加 @ViewChild 并使用 .nativeElement.focus()
组件html:
<div #myerr class="my-error">{{myError}}</div>
组件ts:
export class YourComponent implements AfterViewInit {
@ViewChild('myerr') myErrorText: any;
ngAfterViewInit() {
this.myErrorText.nativeElement.focus();
}
}
您可以通过触发功能更改ngAfterViewInit()。 如果你愿意,你可以给我你的代码,我会调整我的答案。