[英]Angular 4 focus on item on arrow down and scroll
我在div * ngFor循环中有项目,它在所选消息上应用css类'message-list-active'。
app.html
<div id="listText" *ngFor="let message of messages; let i=index" activeIndex = i"
[ngClass]="{'message-list-active': activeIndex === i }">
{{message.name}}
</div>
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++
}
}
app.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;
}
问题是当选择的消息到达列表的末尾时,它将不会滚动。 所以我想要实现的是让所选项目始终集中并能够向下和向上滚动:
这里也有类似的例子:
这是我想要实现的,这是使用jquery jsfiddle http://jsfiddle.net/38zR3/42/回答, 类似的问题/答案,但我怎样才能在Angular 4中使用打字稿来实现这一点
它看起来像这样:
private scrollTo(_index: any) {
let elmnt = document.getElementById(_index);
elmnt.scrollIntoView();
window.scrollTo(0, 0); // only if it's innerhtml
}
这将确保任何焦点的项目都可以进入视图。
在html中需要做类似的事情:
id={{item.uniqueID}} (focus)="scrollTo(item.uniqueID)"
确保使其对使用此功能的所有内容都是唯一的。
编辑
尝试使用html: id="list{{i}}"
if (event.code == "ArrowUp" && this.activeIndex > 0) {
this.activeIndex--
let str = `list${this.activeIndex}`;
let elmnt = document.getElementById(str);
elmnt.scrollIntoView();
window.scrollTo(0, 0);
}
好的,通过制作自定义指令[重点]来修复它
app.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>
Focused.directive:
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){}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.