如何在Angular 4中聚焦和导航li元素?

sta*_*ght 2 html javascript css angular

我正在尝试select在Angular 4中创建自定义选项。但是li当不确定将焦点放在input元素上时如何选择这些选项时,我大吃一惊。

这是我的html代码:

<div class="input-container">
     <input type="text" id="iLocation"
               (focus)="onLocationFocus()"
               (blur)="onLocationBlur()">
     <span class="underline"></span>
     <label for="iLocation">Preferred Type</label>

     <div class="options-container" tabindex="0" #optionsContainerRef>
        <ul>
           <li *ngFor="let loc of locationOptions">{{loc.option}}</li>
        </ul>
     </div>
</div>
Run Code Online (Sandbox Code Playgroud)

这是我的组件打字稿:

locationOptions = [{icon: 'school', option: 'School'}, {icon: 'home', option: 'Home'}];
@ViewChild("optionsContainerRef") optionsContainerRef: ElementRef;
constructor(private renderer: Renderer2) { }
    onLocationFocus() {
      this.renderer.setAttribute(this.optionsContainerRef.nativeElement.children[0].children[0], 'focus', 'true');
    }
    onLocationBlur() {}
Run Code Online (Sandbox Code Playgroud)

即使渲染器添加了focus="true"元素,该li元素也没有被聚焦。我background-color在聚焦时已经编写了css代码li ,但是元素没有聚焦并且颜色没有改变。

我遇到的另一个问题是如何li使用键盘上和下箭头在元素之间导航。在角度4中执行此操作的有效方法是什么?我已经看到了此参考资料,但不确定如何将它做成角度。

请指导并帮助我解决此问题。

Dea*_*alk 5

与其使用焦点,不如使用焦点ngClass-像这样:

在您的组件类中:

  locationOptions = [{ icon: 'school', option: 'School' }, { icon: 'home', option: 'Home' }];
  public focusElement: number = -1;
  constructor() { }
  onLocationFocus() {
    this.focusElement = 0;
  }
  onLocationBlur() {
    this.focusElement = -1;
  }

  onArrowUp() {
    if (this.focusElement > 0) {
      this.focusElement--;
    }
  }

  onArrowDown() {
    if (this.focusElement <= this.locationOptions.length - 2) {
      this.focusElement++;
    }
  }
Run Code Online (Sandbox Code Playgroud)

然后,模板如下所示:

<input type="text" id="iLocation"
               (focus)="onLocationFocus()"
               (blur)="onLocationBlur()"
               (keydown.ArrowUp)="onArrowUp()"
               (keydown.ArrowDown)="onArrowDown()">
     <span class="underline"></span>
     <label for="iLocation">Preferred Type</label>

     <div class="options-container">
        <ul>
            <li #item [ngClass]="{'focus-background': focusElement == item.tabIndex}"
              *ngFor="let loc of locationOptions; let i = index" tabIndex="{{i}}">
             {{loc.option}} </li>
        </ul>
     </div>
Run Code Online (Sandbox Code Playgroud)

和这样的一些CSS

.focus-background {
  background-color: lightblue;
}
Run Code Online (Sandbox Code Playgroud)