当按钮在角度 2 中单击时如何将焦点设置到 div?

New*_*007 9 javascript typescript angular

当单击按钮时,我想将焦点设置在页面顶部的 div 上。这意味着它在单击按钮时验证,如果验证失败,则需要关注页面顶部,验证错误显示。

那么如何获得页面div顶部的焦点。并且形式在模态对话框中。

Rah*_*ngh 11

如果要使不可聚焦的元素成为可聚焦的,则必须为其添加 tabindex 属性并div属于该类别。

更多关于 tabIndex

使用这样的东西

<div tabindex="1"></div>
Run Code Online (Sandbox Code Playgroud)

或者甚至为此制定一个指令,这将帮助您自定义功能

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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)