在angular2 this.fieldRef.nativeElement.focus();在IOS设备中不起作用

时间:2018-01-04 06:54:03

标签: angular

我是angular2的新手并且使用模板创建了一个组件但是在主页上我需要将默认焦点设置为我使用的输入字段

@ViewChild('keyword') // element reference to the keyword textbox.
public searchkeywordref: ElementRef;

ngAfterViewInit() {
    this.searchkeywordref.nativeElement.focus();
    window.scrollTo(0, 0);

}

<section class="searchBlock">
<!-- index page -->
        <div class="searchSection">
                <div class="container">
                    <h2 class="text-center">Service made easy</h2>
                    <div class="selectbar clearfix">
                        <div class="inputBar businessSearchInput border-rt-search dropdown {{ (suggestions?.length > 0) ? 'open' : '' }}">
                            <input placeholder="Search Business" #keyword class="dropdown-toggle text-left" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true" [(ngModel)]="searchKeyword" (ngModelChange)="keywordSuggestions()" (keydown)="arrowkeyLoc($event)" autofocus>
                        </div>                       
                        <div class="searchBtn clearfix customLoader" (click)="searchResult()">
                            
                            <button *ngIf="isloader == false" ><span></span> Search </button>
                            <button *ngIf="isloader == true" ><loaders-css [loader]="'ball-clip-rotate-multiple'" [loaderClass]="'customLoader-ball'"></loaders-css> </button>
                                                       
                        </div>
                    </div>
                </div>
        </div>
    <!-- index page -->
</section>

<!--home component selector binding current location's latitude & longitude -->
    <app-home *ngIf="lat != null" [lat]="lat" [lng]="lng"></app-home>
<!-- home component selector -->

但它不适用于IOS设备。

1 个答案:

答案 0 :(得分:0)

我会尝试将其包装在setTimout中并再次手动运行更改检测:

export class CustomComponent implements OnInit, AfterViewInit {
   constructor(private cd: ChangeDetectionRef){}

   ngAfterViewInit(){
      setTimeout(() => {
         this.searchkeywordref.nativeElement.focus();
         this.cd.detectChanges();
      }, 0)
  }
}