Trying to set Focus using Angular Directive

1749 views angular

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';

  selector: '[myFocus]'
export class FocusDirective implements OnInit {

  @Input('myFocus') isFocused: boolean;

  constructor(private hostElement: ElementRef, private renderer: Renderer2) { }

  ngOnInit() {
    if(this.isFocused) {   

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';

  declarations: [
   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


replace your ngInit method with below code.

ngOnInit() {
    if(this.isFocused) {   
 let timeOut = window.setTimeout(()=>{

posted this

Have an answer?


Please login first before posting an answer.