无法在 angular 2 的 AfterviewInit 中获取 DOM 元素引用,超时也能够在 Chrome 而非 IE 中设置焦点
Unable to fetch DOM element reference in AfterviewInit in angular 2, also with timeout able to set focus in Chrome not IE
强制使用 setTimeout()
,在 chrome 中工作正常但在 IE 中不工作
ngAfterViewInit(){
setTimeout(()=>{
this.businessInfoName._inputElement.nativeElement.focus();
},2000);
}
<md-input
class="firstField"
autofocus
[ngClass]="{submitted:searchClicked}"
#businessInfoName
[(ngModel)]="submission.accountHolderCompany.contactName"
aria-placeholder="Name of Business"
placeholder="Name of Business"
required
name="businessname"
(focus)="v_businessName = true"
(blur)="v_businessName = false;replaceSpacesWithEmpty()"
#businessName="ngModel"
restrictKey
maxlength="50"
></md-input>
不要在组件范围内引用元素,而是使用 ViewChild
装饰器获取对 class 中元素的引用,然后像这样在 ngAfterViewInit
中引用它:
@ViewChild('businessInfoName') businessInfoNameRef: TemplateRef;
ngAfterViewInit(){
this.businessInfoNameRef.nativeElement.focus();
}
Demo
强制使用 setTimeout()
,在 chrome 中工作正常但在 IE 中不工作
ngAfterViewInit(){
setTimeout(()=>{
this.businessInfoName._inputElement.nativeElement.focus();
},2000);
}
<md-input
class="firstField"
autofocus
[ngClass]="{submitted:searchClicked}"
#businessInfoName
[(ngModel)]="submission.accountHolderCompany.contactName"
aria-placeholder="Name of Business"
placeholder="Name of Business"
required
name="businessname"
(focus)="v_businessName = true"
(blur)="v_businessName = false;replaceSpacesWithEmpty()"
#businessName="ngModel"
restrictKey
maxlength="50"
></md-input>
不要在组件范围内引用元素,而是使用 ViewChild
装饰器获取对 class 中元素的引用,然后像这样在 ngAfterViewInit
中引用它:
@ViewChild('businessInfoName') businessInfoNameRef: TemplateRef;
ngAfterViewInit(){
this.businessInfoNameRef.nativeElement.focus();
}