如何在Angular 2中点击按钮时将焦点设置为div?

9
我希望在单击按钮时将焦点设置到页面顶部的 div。这意味着当点击按钮时进行验证,如果验证失败,则需要将焦点聚焦到页面顶部,即验证错误所在的位置。
因此,如何将焦点聚焦到页面顶部的 div 呢?表单位于 modal-dialog 中。

你试过这个angular.element('#<elementId>').focus(); 吗?否则还有许多onfocus指令可以处理此问题。 - Hrishikesh Kale
我尝试过了,但是不起作用。 - Newbie007
2个回答

16

如果您想使一个非可聚焦元素变为可聚焦,必须向其添加 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();
    }
  }
}

感谢您添加了使用指令的解决方案。 - userx

3
你可以在组件中尝试添加一个@ViewChild并使用.nativeElement.focus() 组件html :
<div #myerr class="my-error">{{myError}}</div>

组件 ts:

 export class YourComponent implements AfterViewInit {
   @ViewChild('myerr') myErrorText: ElementRef;


  ngAfterViewInit() {
    this.myErrorText.nativeElement.focus();
  }
}

您可以根据您的触发函数更改ngAfterViewInit()。 如果您愿意,您可以将您的代码给我,我会适应并回答您的问题。

1
这个代码不起作用,出现了错误:ERROR TypeError: Cannot read property 'nativeElement' of undefined - Deepak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接