2016-03-02 22 views
6

正如你所看到的,我正在使用setTimeout,如果我打算專注於我的輸入。 如果我刪除setTimeout焦點不起作用。如果我不使用超時,則角度2焦點不起作用

<div [hidden]="searchInputHidden"> 
     <input (blur)="hideInput()" #term (keyup)="search(term.value)" type="text" class="inp_top" name="product_name" id="product_name" /> 
    </div> 


private showSearchInput(term) { 
    this.searchInputHidden = false; 
    setTimeout(function(){ 
     term.focus(); 
    }, 100); 
    } 

回答

14

超時是必需的,因爲您不能focus()仍然隱藏的元素。直到角度更改檢測有機會運行(在方法showSearchInput()完成執行後),即使在方法中將searchInputHidden設置爲false,DOM中的hidden屬性也不會更新。

A setTimeout()值爲0(或沒有值,默認爲0)應該工作。您只需在Angular獲得更新hidden屬性值的機會後設置焦點。


注意,setTimeout()回調函數執行完畢後,變化檢測將再次運行(因爲角度猴子補丁是在角區的所有setTimeout()調用)。由於我們是在我們的異步回調函數變化的唯一的事情是關注的焦點,我們可以更加高效,運行我們的回調函數的角度帶外,以避免額外的變更檢測週期:

private showSearchInput(term) { 
    this.searchInputHidden = false; 
    this._ngZone.runOutsideAngular(() => { 
    setTimeout(() => term.focus()); 
    }); 
} 

注意,你」將不得不注入NgZone到您的構造函數上面的代碼工作:

export class YourComponent { 
    constructor(private _ngZone: NgZone) {} 
-1

也許你可以嘗試這樣的事:

<div class="row col-md-12" [hidden]="messagehide"> 
{{_result.msgDesc}} 
</div> 
`this.messagehide=false; 
this.messagealert(); 
messagealert(){ 
setTimeout(function() { 
this.messagehide=true;   
},3000); 
}` 

My settimeout function also didn't work . let me know.