如何滚动查看下拉框的选定元素?我遇到了这个问题。对于angular2模式,我没有参考html li标签。滚动滑块应在选择输入字段后移动,并使用向下箭头键进行输入。什么应该是最好的做法?请问有什么解决方案吗?
import { bootstrap } from 'angular2/platform/browser';
import { Component, View } from 'angular2/core';
import { NgFor, FORM_DIRECTIVES, NgClass } from 'angular2/common';
export class Model {
constructor(public itemId: number, public value: string, public isFocused: boolean) { }
}
@Component({selector: "app"})
@View({template: `
<style>
.drmenu {position: absolute; z-index: 1000; min-width: 250px; background-color: #fff;
border: 1px solid rgba(0,0,0,.15); max-height: 60px; overflow-x: hidden;}
.itemBackground {background-color: red;}
.selectedItemBackground {background-color: green;}
</style>
<div style="position: relative;">
<input (keydown)="onKeydown($event)"/>
<ul class="drmenu">
<li *ngFor="#item of items">
<div [ngClass]="{itemBackground: item.isFocused, selectedItemBackground: !item.isFocused}">{{item.value}}</div>
</li>
</ul>
</div>
`,
directives: [NgClass, NgFor]
})
class AppComponent {
items: Array<Model> = [new Model(1, "I1", false), new Model(1, "I2", false), new Model(1, "I3", false), new Model(1, "I4", false), new Model(1, "I5", false), new Model(1, "I6", false)];
private onKeydown(event: KeyboardEvent) {
var keyCode = event.which || event.keyCode;
var focusedIndex = this.items.findIndex(i => i.isFocused);
switch (keyCode) {
case 38:
if (focusedIndex > 0) {
this.items[focusedIndex].isFocused = false;
this.items[focusedIndex - 1].isFocused = true;
}
break;
case 40:
if (focusedIndex < this.items.length) {
if (focusedIndex > -1) { this.items[focusedIndex].isFocused = false; }
this.items[focusedIndex + 1].isFocused = true; }
break;
}
}
}
bootstrap(AppComponent);
答案 0 :(得分:2)
我终于通过实现一个指令并将<li>
引用映射到我的模型来解决这个问题:
<li *ngFor="#item of items" [dirItemId]=item.itemId (elementCreated)="elementCreated($event)">