使用指令设置元素焦点

问题描述 投票:0回答:1

我试图获得一个Angular Directive来控制以编程方式设置元素的焦点。

这是我的指令在组件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()方法中设置焦点的步骤出了问题。

angular angular-directive
1个回答
0
投票

你可以使用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();
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.