使用指令设置元素焦点
Set element focus using a directive
我正在尝试获取 Angular 指令来控制以编程方式将焦点设置在元素上。
这是我的指令在组件 html 中的样子:
<input type="text" class="form-control"
[(ngModel)]="inputText" [myFocus]="isFocused">
我的指令如下所示:
import { Directive, OnInit, ElementRef, Renderer2, Input } from '@angular/core';
@Directive({
selector: '[myFocus]'
})
export class FocusDirective implements OnInit {
@Input('myFocus') isFocused: boolean;
constructor(private hostElement: ElementRef, private renderer: Renderer2) { }
ngOnInit() {
if(this.isFocused) {
this.renderer.selectRootElement(this.hostElement.nativeElement).focus();
}
}
}
然后在组件代码中我改变了这个:
this.isFocused = true;
该指令包含在 app.module.ts 中,如下所示:
import { FocusDirective } from './directives/focus.directive';
@NgModule({
declarations: [
FocusDirective
],
bootstrap: [AppComponent]
})
export class AppModule { }
但是,当我这样做时,焦点似乎没有设置好。
我知道 Renderer2 的工作方式发生了一些相当大的变化,我假设我在 ngOnInit() 方法中设置焦点的步骤出了问题。
您可以使用 nativeElement.focus()
来实现
import { Directive, OnInit, ElementRef, Renderer2, Input } from '@angular/core';
@Directive({
selector: '[myFocus]'
})
export class FocusDirective implements OnInit {
@Input('myFocus') isFocused: boolean;
constructor(private hostElement: ElementRef, private renderer: Renderer2) { }
ngOnChanges() {
if(this.isFocused) {
this.hostElement.nativeElement.focus();
}
}
}
我正在尝试获取 Angular 指令来控制以编程方式将焦点设置在元素上。
这是我的指令在组件 html 中的样子:
<input type="text" class="form-control"
[(ngModel)]="inputText" [myFocus]="isFocused">
我的指令如下所示:
import { Directive, OnInit, ElementRef, Renderer2, Input } from '@angular/core';
@Directive({
selector: '[myFocus]'
})
export class FocusDirective implements OnInit {
@Input('myFocus') isFocused: boolean;
constructor(private hostElement: ElementRef, private renderer: Renderer2) { }
ngOnInit() {
if(this.isFocused) {
this.renderer.selectRootElement(this.hostElement.nativeElement).focus();
}
}
}
然后在组件代码中我改变了这个:
this.isFocused = true;
该指令包含在 app.module.ts 中,如下所示:
import { FocusDirective } from './directives/focus.directive';
@NgModule({
declarations: [
FocusDirective
],
bootstrap: [AppComponent]
})
export class AppModule { }
但是,当我这样做时,焦点似乎没有设置好。 我知道 Renderer2 的工作方式发生了一些相当大的变化,我假设我在 ngOnInit() 方法中设置焦点的步骤出了问题。
您可以使用 nativeElement.focus()
来实现import { Directive, OnInit, ElementRef, Renderer2, Input } from '@angular/core';
@Directive({
selector: '[myFocus]'
})
export class FocusDirective implements OnInit {
@Input('myFocus') isFocused: boolean;
constructor(private hostElement: ElementRef, private renderer: Renderer2) { }
ngOnChanges() {
if(this.isFocused) {
this.hostElement.nativeElement.focus();
}
}
}