【问题标题】:On Key `Enter` trigger click event on active list item AngularOn Key `Enter` 触发活动列表项 Angular 上的单击事件
【发布时间】:2019-05-14 07:24:45
【问题描述】:

我做了一个水平滚动,里面有资源。 我正在使用箭头键在列表中导航,现在我想通过单击 Enter 打开那个特定的突出显示列表。

组件.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 键,那么我想打开该资源。

【问题讨论】:

  • 打开是指导航?因为在这种情况下你可以添加var win = window.location(resource.url, '_blank'); win.focus();
  • 通过导航,我的意思是当我使用箭头键在列表数据之间切换时,在我点击Enter 键的任何列表项上,它都会触发该特定列表项的 HTML 中的 Anchor 标记。跨度>

标签: angular angular7 keyup onfocus


【解决方案1】:

我得到了结果:

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

        });

      }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 2016-10-22
    • 2013-11-28
    相关资源
    最近更新 更多