2017-08-09 42 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