Angular 4 专注于向下箭头上的项目并滚动

Ale*_*FF1 5 javascript css keyboard-events typescript angular

我在 div *ngFor 循环中有项目,它在所选消息上应用 css 类“message-list-active”。

应用程序.html

 <div  id="listText" *ngFor="let message of messages; let i=index" activeIndex = i" 
   [ngClass]="{'message-list-active': activeIndex === i  }">
      {{message.name}}
 </div>
Run Code Online (Sandbox Code Playgroud)

component.ts //使用上下箭头选择消息监听键盘事件

  messages;  // we have date stored here
  activeIndex = 0;


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


  if (event.code == "ArrowUp" && this.activeIndex > 0) {
    this.activeIndex--

   }
  if (event.code == "ArrowDown" && this.activeIndex < this.messages.length-1) {
    this.activeIndex++

  }
 }
Run Code Online (Sandbox Code Playgroud)

应用程序.css

    #listText {
        width: auto;
        height:100%;
        overflow: auto
      }

     .message-list-active {
        margin: 0;
        padding: 15px 15px 5px 13px;
        border-radius: 0;
        background-color: #CDE6F7;
        border-style: dotted;
        border-width: 1px;
        border-bottom: 1px dotted;
         }
Run Code Online (Sandbox Code Playgroud)

问题是当所选消息到列表的末尾时,它将不会滚动。所以我想要实现的是让所选项目始终聚焦并且能够向下和向上滚动:

这里也有类似的例子:

在此处输入图片说明

这是我试图实现的,这是使用 jquery jsfiddle http://jsfiddle.net/38zR3/42/回答的,类似的问题/答案,但如何使用打字稿在 Angular 4 中实现这一点

Ale*_*FF1 2

好的,通过制定自定义指令来修复它[重点]

应用程序.html

     <div id="listText">
        <div *ngFor="let message of messages; [focused]="i === activeIndex" let i=index" activeIndex = i" 
          [ngClass]="{'message-list-active': activeIndex === i  }">
       {{message.name}}
  </div>
Run Code Online (Sandbox Code Playgroud)

重点指令:

  import {Directive, Input, Renderer, ElementRef} from '@angular/core'

  @Directive({
   selector: '[focused]'
     })

 export class FocusedDirective {

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

  constructor(private elementRef: ElementRef, private renderer: Renderer){}
   }
Run Code Online (Sandbox Code Playgroud)