0

I want to try to focus the next focusable element when pressing enter in an input. If tried the approach from Focus Next Element In Tab Index but it does not seem to work

The variable focusableElements consists of the correct elements in the right order, but I am no able to focus or blur them. Also I have tried to change the innerText of the elements, which worked neither, but it is interesting that binding event handlers work as you can see in the ngAfterViewInit

I have also tried it with a setTimeout of 500 seconds, but this didnt change anything

Code:

 constructor(private el:ElementRef)

 ngAfterViewInit() {
    let inputs =  this.el.nativeElement.querySelectorAll("input") as HTMLInputElement[];
    for(let i = 0; i<inputs.length; i++) {
      console.log(inputs[i])
      inputs[i].onkeydown = this.handleEnterFocus.bind(this);
    }
  }

 public handleEnterFocus($event) {
      if($event.key !== 'Enter') return;

      var focussableElements = 'a:not([disabled]), button:not([disabled]), input:not([disabled]), [tabindex]:not([disabled]):not([tabindex="-1"])';
      if (this.el.nativeElement && this.el.nativeElement) {
          var focussable = Array.prototype.filter.call(this.el.nativeElement.querySelectorAll(focussableElements),
          function (element) {
              return element.offsetWidth > 0 || element.offsetHeight > 0 
          });
          var index = focussable.indexOf(document.activeElement);
          if(index > -1) {
             var nextElement = focussable[index + 1];
                focussable[0].blur()
               nextElement.focus();
          }      
        }
        $event.preventDefault();

  }

vazun
  • 145
  • 1
  • 8

0 Answers0