1)在您组件模板的输入中添加一个模板变量引用:
<ion-input #textInput>
Run Code Online (Sandbox Code Playgroud)
2)在组件的导入中添加ElementRef和ViewChild:
import { ElementRef, ViewChild } from '@angular/core'
Run Code Online (Sandbox Code Playgroud)
3)@ViewChild在您的组件中添加变量和相关方法:
export class AppComponent {
@ViewChild('textInput') textInput;
setFocus() {
this.textInput.nativeElement.focus();
}
removeFocus() {
this.textInput.nativeElement.blur();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以触发setFocus()或removeFocus()以多种方式触发。这是一个例子:
# app.component.html
<ion-input #textInput>
# app.component.ts
import { HostListener } from '@angular/core';
export class AppComponent {
[previous code elided for readability]
isInputActive: boolean;
@HostListener('document:click', ['$event'])
handleClickEvent(event: MouseEvent): void {
if (document.activeElement !== this.textInput.nativeElement) {
this.textInput.nativeElement.blur();
}
}
}
Run Code Online (Sandbox Code Playgroud)