在活动输入项Angular上的Enter键触发点击事件

时间:2019-05-14 07:24:45

标签: angular angular7 keyup onfocus

我用资源进行了水平滚动。 我正在使用箭头键在列表中导航,现在我想通过单击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) { 
  }

}

现在,我要在列表上导航时触发点击,如果我按了enter键,那么我想打开该资源。

1 个答案:

答案 0 :(得分:0)

我得到的结果是:

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

        });

      }
    }