简体   繁体   中英

How can I set focus on first input field on each page in my whole application in angular 6

My application is in final stages and we have not implemented autofocus on input tags. Now we have a requirement where we wish to put focus on first input tag in each of the page. There are lot of pages/forms in my application, so using ViewChild in each component can be a tedious task. Hence I'm looking for some way from which I can write some code at one place and it triggers focus on first input on whatever page is loaded. Can anyone suggest some way to do this?

You can subscribe to router events in your app component and if even is instance of navigationEnd means route change occur then get first input on page and focus using jquery something like below in your app component constructor

 router.events.subscribe((e) => {
      if(e instanceof NavigationEnd)
        {
         var ele= $('input[type=text],textarea').filter(':visible:first').focus();
        }
    });

Working demo

I came up with a method decorator which would do what you want. That is, if you don't mind to import this function to all pages. You would then simply attach this decorator to the AfterViewInit life cycle, like so:

@setFocus()
ngAfterViewInit() { }

The decorator function would then search after the first input field found and if found, set focus to that element:

export function setFocus(): MethodDecorator {
  return function (target: Object, key: string, descriptor: PropertyDescriptor) {
    descriptor.value = function (...args: any[]) {
      const ele = document.getElementsByTagName("INPUT")[0] as HTMLElement;
      if (ele) {
        ele.focus();
        return;
      }
    }
  }
}

STACKBLITZ

you can use tabindex property of HTML element with tabindex="1" will receive focus first

eg:

see: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex : https://developer.paciellogroup.com/blog/2014/08/using-the-tabindex-attribute/

NB: Be careful using tabindex as it imposes a tab order on the content that bears no resemblance to the expected tab order.

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