Установить фокус элемента с помощью директивы - PullRequest
0 голосов
/ 04 ноября 2018

Я пытаюсь получить угловую директиву для управления настройкой фокуса на элементе программно.

Вот как выглядит моя директива в 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 ().

1 Ответ

0 голосов
/ 04 ноября 2018

Вы можете достичь с помощью 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();
    }
  }
}
...