On Key `Enter` trigger click event on active list item Angular
Asked Answered
S

1

0

I made a horizontal scroll with resources in it. I'm using the arrow key to navigate in the list, now I want to open that particular highlight list by clicking enter.

Component.ts

arrowkeyLocation = 0;

  @HostListener('document:keydown', ['$event'])
    keyDown(event: KeyboardEvent, resource): void {

      if (event.keyCode === 37 && this.arrowkeyLocation > 0) {
        this.arrowkeyLocation--;
      }

      if (event.keyCode === 39 && this.arrowkeyLocation < this.searchData.toArray().length - 1 ) {
        this.arrowkeyLocation++;
      }

      if (event.keyCode === 13) {
        // do your code here**
        console.log(item);
      }
    }

HTML

<div #myVar [appSearchfocus]="i === arrowkeyLocation" *ngFor="let resource of all_resources | searchResource: message; let i=index" [ngClass]="{'active': arrowkeyLocation === i }"(keydown)="keyDown($event, resource)" >
    <a target="_blank" href={{resource.url}} class="noDecoration">
        <div >
          <p><b>{{ resource.title }}</b></p>
        </div>
    </a>
</div>

directive.ts

@Directive({
  selector: '[appSearchfocus]'
})
export class SearchfocusDirective {

  @Input()
      set appSearchfocus(value: boolean){
         if(value){
           this.renderer.invokeElementMethod(this.elementRef.nativeElement, 'scrollIntoViewIfNeeded');
         }
    }

  constructor(private elementRef: ElementRef, private renderer: Renderer) { 
  }

}

Now, what I want to trigger click while navigating on the list and if I hit enter key then I want to open that resource.

Slew answered 14/5, 2019 at 7:24 Comment(2)
With open you mean navigate? Cause in that case you can just add var win = window.location(resource.url, '_blank'); win.focus();Vernissage
by navigate, i meant when i am switching between list data using arrow keys, on whichever list item I hit Enter key, it triggers that Anchor tag in HTML of that particular list item.Slew
S
0

I got the result using:

if (event.keyCode === 13) {
        this.searchData.forEach(element => {
          if (element.nativeElement.classList.contains('active') ) {
            let check: HTMLElement = element.nativeElement.getElementsByTagName("a").item(0);
            check.click(); 
          }

        });

      }
    }
Slew answered 14/5, 2019 at 11:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.