最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set focus to the div when button click in angular 2? - Stack Overflow

programmeradmin4浏览0评论

I want to set focus to the div which is top of the page when clicking the button. It means it validates when click the button, if validation fails, it need to focus the top of the page, where the validation error shows.

So how to get the focus the top of the page div. And form is in modal-dialog.

I want to set focus to the div which is top of the page when clicking the button. It means it validates when click the button, if validation fails, it need to focus the top of the page, where the validation error shows.

So how to get the focus the top of the page div. And form is in modal-dialog.

Share Improve this question edited Oct 24, 2021 at 18:35 Tharindu Lakshan 6,1167 gold badges30 silver badges50 bronze badges asked Feb 12, 2018 at 5:59 Newbie007Newbie007 1691 gold badge5 silver badges13 bronze badges 2
  • have you tried this angular.element('#<elementId>').focus(); ? or else there are many onfocus directive to handle this. – Hrishikesh Kale Commented Feb 12, 2018 at 6:05
  • I tried, but not working – Newbie007 Commented Feb 12, 2018 at 6:09
Add a comment  | 

2 Answers 2

Reset to default 18

If you want to make a non-focusable element focusable, you must add a tabindex attribute to it and div falls in that category .

More on tabIndex

use some thing like this

<div tabindex="1"></div>

or even make a directive for the same which will help you customize the functionality

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();
    }
  }
}

You can try to add a @ViewChild in your component and use .nativeElement.focus()

component html :

<div #myerr class="my-error">{{myError}}</div>

component ts :

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


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

You can change ngAfterViewInit() by your triggering function. If you want, you can give me your code and I adapt my answer.

发布评论

评论列表(0)

  1. 暂无评论