Trying to set Focus using Angular Directive

1746 views angular
0

I am trying to get an Angular Directive to control setting the focus on an element programmatically.

Here is what my directive looks like in the component html:

<input type="text" class="form-control"
    [(ngModel)]="inputText" [myFocus]="isFocused">

Here is what my directive looks like:

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();
    }
  }
}

Then in the component code I change the the

this.isFocused = true;

The directive is included in the app.module.ts like so:

import { FocusDirective } from './directives/focus.directive';

@NgModule({
  declarations: [
    FocusDirective
  ],
   bootstrap: [AppComponent]
})
export class AppModule { }

However, the focus does not seem to get set when I do this. I understand there has been some fairly big changes to how the Renderer2 works and I assume I am getting something wrong with my step of setting the focus in the ngOnInit() method.

All help appreciated

answered question

1 Answer

11

replace your ngInit method with below code.

ngOnInit() {
    if(this.isFocused) {   
 let timeOut = window.setTimeout(()=>{
 window.clearTimeout(timeOut)
 this.renderer.selectRootElement(this.hostElement.nativeElement).focus();
 },100)
    }
  }

posted this

Have an answer?

JD

Please login first before posting an answer.