2016-08-02 80 views
1

我想打開一個模式窗口,並在其中輸入焦點。Angular 2.focus()不起作用

在HTML文件中

<img id='searchIcon' 
    src="images/search.png" 
    class="icon iconCenter" 
    data-toggle="modal" 
    data-target="#myModal" 
    (click)='focusSearch();' /> 

<div id="myModal" class="modal fade modal-container" role="dialog"> 
    <h3>SEARCH</h3> 
    <input id='inputSearch' type="text" autofocus> 
</div> 

隨着自動對焦屬性我關注我第一次打開模態視圖

,但之後我關閉和開啓模式又沒有做任何事情。(在Firefox不工作的時候)

在TS

文件

focusSearch(){ 
    document.getElementById("inputSearch").focus(); 
} 

如果有人可以留下一個快速演示我將不勝感激

+0

一個很好的指令,使這更容易http://stackoverflow.com/questions/34522306/angular-2-focus-on-newly-added-input-element不知道你可以將它用於您的用例。 –

+0

@GünterZöchbauer我不知道如何將它應用到我的 – angel

+1

@PankajParkar它已經有自動對焦並且不起作用 – angel

回答

0

試試這個,沒有一個功能

<img id='searchIcon' src="images/search.png" class="icon iconCenter" data-toggle="modal" data-target="#myModal" (click)='myInput.focus()'> 
    <div id="myModal" class="modal fade modal-container" role="dialog"> 
     <h3>SEARCH</h3> 
     <input id='inputSearch' type="text" autofocus #myInput> 
    </div> 
+0

沒有工作,說在點擊中的#是一個錯誤 – angel

+0

它應該現在工作,我有刪除'#','(點擊)='myInput.focus()'' – AngJobs

+0

這裏是一個工作版本,https://plnkr.co/edit/C7OzBW?p=preview – AngJobs

0

將焦點設置例如

的Html

<button (click)="setFocus()">Set Focus</button> 
    <input type="text" [(ngModel)]="term2" #inputBox> 

組件

import { Component, ViewChild, ElementRef } from '@angular/core'; 

@Component({ 
    selector: 'app-general', 
    templateUrl: './general.component.html', 
    styleUrls: ['./general.component.scss'] 
}) 
export class GeneralComponent { 

    @ViewChild("inputBox") _el: ElementRef; 

    setFocus() { 
    this._el.nativeElement.focus(); 
    } 
} 

您可以根據需要修改代碼。您也可以在組件加載後設置焦點。例如

ngAfterViewInit() { 
    this._el.nativeElement.focus(); 
    } 

More Info