我在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/,similar question/answer来回答的,但是如何使用typescript
在Angular 4中实现这一点答案 0 :(得分:1)
看起来像这样:
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);
}
答案 1 :(得分: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){}
}