【问题标题】:Set element focus using a directive使用指令设置元素焦点
【发布时间】:2018-11-04 12:52:40
【问题描述】:

我正在尝试获取 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() 方法中设置焦点的步骤有问题。

【问题讨论】:

标签: angular angular-directive


【解决方案1】:

你可以使用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();
    }
  }
}

【讨论】:

  • 我应该工作。你可能做错了什么。参考stackoverflow.com/questions/38307060/…
  • 尝试使用 ngOnChanges 生命周期方法。更新了代码
  • @SureshKumarAriya 所以基本上是现有答案的复制粘贴,嗯?
  • 不,我根据我验证并更新了代码的反馈添加了代码。
  • Angular 团队不鼓励直接操作 DOM。它容易受到 XSS 攻击。您应该改用 Renderer2
猜你喜欢
  • 2014-12-25
  • 1970-01-01
  • 2018-10-05
  • 1970-01-01
  • 2020-05-15
  • 2015-11-05
  • 2018-03-25
  • 1970-01-01
  • 2015-06-12
相关资源
最近更新 更多