简体   繁体   English

如何设置焦点在Angular 2中下拉列表的第一个列表项

[英]How to set Focus on the first list item of a dropdown in Angular 2

My template contains a dynamic list: 我的模板包含一个动态列表:

<mydropdown>
    <li *ngFor="let cookie of cookies" [class.disabled]="cookie.disabled">
        <a href="#">
            <span>{{cookie}}</span>            
        </a>
    </li>
</mydropdown>

This dropdown is opened when clicked on a button until then it's not in the DOM. 单击按钮时会打开此下拉列表,直到它不在DOM中。

I have implemented a focus directive as follows: 我已经实现了一个焦点指令如下:

import { Directive, ElementRef, Input } from "@angular/core";

@Directive({
    selector: "[myFocus]"
})
export class Focus {
    @Input('myFocus') indx: boolean;
    constructor(private _el: ElementRef) {

    }

    ngOnInit() {
         if(this.indx){
           this._el.nativeElement.focus();
         }
    }

}

Usage: I am calling the myFocus on the list element of the template as follows: 用法:我在模板的list元素上调用myFocus,如下所示:

<mydropdown>
        <li *ngFor="let cookie of cookies; let indx=index" [myFocus]="!indx" [class.disabled]="cookie.disabled">
            <a href="#">
                <span>{{cookie}}</span>            
            </a>
        </li>
    </mydropdown>

So, I am trying to get the focus on the first list item of the dropdown. 所以,我试图把焦点放在下拉列表的第一个列表项上。

When I debug the code, I do enter my focus code and the this._el contains the list item. 当我调试代码时,我输入我的焦点代码, this._el包含列表项。 So, the focus is getting called on the list item. 因此,重点是在列表项上调用。 But the focus state doesn't show up on the list item of the dropdown. 但焦点状态不会显示在下拉列表项列表中。

Am I doing something wrong? 难道我做错了什么? Should I do this after the view has been loaded completely or should I subscribe to something? 我应该在视图完全加载后还是应该订阅某些内容时执行此操作? Could anyone guide me in a right direction. 谁能引导我朝着正确的方向前进

You need to add attribute tabindex="-1" to your li elements. 您需要将属性tabindex="-1"到li元素中。

PS: If you add [attr.tabindex]="indx" it will not work, don't know why yet. PS:如果你添加[attr.tabindex]="indx"它将无法正常工作,不知道为什么。

Here is an Example 这是一个例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM