简体   繁体   中英

How to set focus to the div when button click in angular 2?

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 .

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.

try something like that

component.html

 <div #topElement> </div>
 <button (click)="changeFocus()"> change Focus </button>

component.ts

export default class MyComponent {
 changeFocus() {
     window.location.hash = '#topElement';
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM