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




<input type="text" class="confirmBox" [(ngModel)]="confirmLocation" placeholder="Scan Material" autofocus/>








autofocus。

。。

========================今天又遇到tab 切换之后,还是获取不到焦点

解决方法:


Angular 4 文本框自动获取焦点_解决方法


Angular 4 文本框自动获取焦点_Angular_02


Angular 4 文本框自动获取焦点_解决方法_03


Angular 4 文本框自动获取焦点_解决方法_04

html:


<td style="width:10%">



<input type="text" #box [ngClass]="{'confirmBox': classFlag, 'confirmBoxError': !classFlag}" [(ngModel)]="confirmLocation" (ngModelChange) ="checkscan($event)"



placeholder="Scan Material" autofocus="autofocus" (keyup.enter)="onEnter(box.value)" />



</td>






ts:



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



constructor(public renderer: Renderer, private el: ElementRef, private service: PickDeliveryOrdersService, private router: Router, private modalService: NgbModal) { };



ngOnInit(): void {



this._success.subscribe((message) => { this.successMessage = message; this.errorMessage = ''; });



this._error.subscribe((message) => { this.errorMessage = message; this.successMessage = ''; });



debounceTime.call(this._success, 5000).subscribe(() => this.successMessage = '');



debounceTime.call(this._error, 5000).subscribe(() => this.errorMessage = '');



this.service.reasonTypes(2).subscribe(r => this.reasons = r);



this.loadTopQueueDeliveryOrder();



// document.getElementById('box').focus();



// console.log(document.getElementById('box'));



}



// tslint:disable-next-line:use-life-cycle-interface



ngAfterViewInit() {



console.log('AfterViewInit之后');



this.renderer.invokeElementMethod(



this.infocus.nativeElement, 'focus');



}