2017-08-09 44 views
3

我有ul> li的div,显示在ngIf执行下面的广告后。Angular 2在ngIf执行后将焦点集中在ul li上

<input type="text" /> 
<button (click)="ShowDropDown=true;">Show</button> 
<div *ngIf="ShowDropDown"> 
    <ul> 
    <li (mousedown)="...">...</li> 
    <li (mousedown)="...">...</li> 
    <li (mousedown)="...">...</li> 
    </ul> 
</div> 

我需要在单击显示按钮后,将重点放在ul> li的第一个元素上。

+0

我见过这个习惯“自动对焦”指令完成。 https://material.angularjs.org/1.0.4/api/directive/mdAutofocus(我知道这个链接是针对角度1的,但基本思路应该是相同的) –

+0

使用'ngStyle'来添加'focus'风格html –

回答

3

我已更新我的解决方案以使用getter/setter。 我添加@Faisal提到的tabindex。 模板:

<button (click)="showDropDown=true;">Show</button> 
<div #container> 
<div *ngIf="showDropDown"> 
    <ul> 
    <li tabindex="0" (mousedown)="select">1</li> 
    <li (mousedown)="select">2</li> 
    <li (mousedown)="select">3</li> 
    </ul> 
</div> 
</div> 

而在组件:

private _showDropDown = false; 

    get showDropDown() { 
    return this._showDropDown; 
    } 

    set showDropDown (val) { 
    this._showDropDown = val; 
    this.focusOnFirstLi(); 
    } 

    @ViewChild('container') myDiv; 

    focusOnFirstLi() { 
    var that = this; 
    setTimeout(function() { 
     that.myDiv.nativeElement.getElementsByTagName("li")[0].focus(); 
    }, 10); 
    } 

https://plnkr.co/edit/Dc3Eh35QX9kiHg3YsSBR?p=info

+0

foo.nativeElement给出了未定义。 –

+0

这会给出错误,因为#foo元素还没有被初始化,因为* ngIf – Faisal

+0

是否可以扩展为向下箭头和向上箭头以通过ul> li元素进行导航? –

3

对于像divli元素将焦点设置等,需要设置一个tabindex属性他们。这里是你如何将焦点设置按钮点击:

您的组件的HTML改成这样:

<button (click)="showDropDown()">Show</button> 
<div *ngIf="toggleDropDown"> 
    <ul> 
    <li #firstLi tabindex="0">...</li> 
    <li >...</li> 
    <li >...</li> 
    </ul> 
</div> 

......在你的组件类:

toggleDropDown: boolean = false; 
    @ViewChild('firstLi') firstLi:ElementRef; 
    public showDropDown(){ 
     this.toggleDropDown=true 
     setTimeout(()=>{ 
     this.firstLi.nativeElement.focus(); 
     },10); 
    } 

这里是一个工作plunker:DEMO