角度5:无法将输入元素设置为焦点。 @ViewChild和nativeElement.focus()在除Safari移动版以外的所有浏览器中都很好用:
HTML:
<div>
<input #inputElement1 placeholder="input element 1" *ngIf="isVisible"/>
</div>
<button (click)="toggleInput();">show input</button>
TS:
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
isVisible = false;
@ViewChild("inputElement1") inputEl: ElementRef;
toggleInput() {
this.isVisible = !this.isVisible;
setTimeout(() => {
if (this.inputEl) {
this.inputEl.nativeElement.focus();
}
}, 0);
}
}