Angular Directive not setting focus properly on recently disabled input





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I have an input field that I want to disable when a user presses the 'enter' key. It will then try and fetch a user details. When it has fetched the details or there has been an error, I want to enable the input field again and set the focus on that field.



I am using this directive to set the focus on the input field:



import { Directive, OnChanges, ElementRef, Input } from '@angular/core';

@Directive({
selector: '[myFocus]'
})
export class FocusDirective implements OnChanges {

@Input('myFocus') isFocused: boolean;
constructor(private hostElement: ElementRef) { }

ngOnChanges() {
if(this.isFocused) {
this.hostElement.nativeElement.focus();
}
}
}


It is implemented in the html like so:



<input type="text" class="form-control" [(ngModel)]="text"
[myFocus]="isFocused" [disabled]="disableInput"
(keydown)="podcastsKeyDown($event)">


The podcastKeyDown() function looks like this:



podcastsKeyDown(event) {
if(event.keyCode == 13) {
this.disableInput = true;
this.getUser(this.text).subscribe(account => {
this.disableInput = false;
this.isFocused = true;
});
}
}


When the user account has successfully returned i set the input field to be enabled, which works correctly. However the focus is not returned to this input. I have tried placing a timeout around re-setting the focus just in case there is some timing issue, however this did not work either. The code looked like this:



setTimeout(() => {
this.isPodcastNamesFocused = true;
}, 100);


Any ideas what is happening here and how to fix it?



Thanks in Advance.



EDIT 1: To be precise - it actually works the first time when using the timeout, but for subsequent user entries it does not...










share|improve this question

























  • Try with ngOnChanges(changes) { if (changes.isFocused.currentValue) ...

    – trichetriche
    Nov 16 '18 at 12:33











  • @trichetriche this did not work

    – Tom O'Brien
    Nov 16 '18 at 12:46


















1















I have an input field that I want to disable when a user presses the 'enter' key. It will then try and fetch a user details. When it has fetched the details or there has been an error, I want to enable the input field again and set the focus on that field.



I am using this directive to set the focus on the input field:



import { Directive, OnChanges, ElementRef, Input } from '@angular/core';

@Directive({
selector: '[myFocus]'
})
export class FocusDirective implements OnChanges {

@Input('myFocus') isFocused: boolean;
constructor(private hostElement: ElementRef) { }

ngOnChanges() {
if(this.isFocused) {
this.hostElement.nativeElement.focus();
}
}
}


It is implemented in the html like so:



<input type="text" class="form-control" [(ngModel)]="text"
[myFocus]="isFocused" [disabled]="disableInput"
(keydown)="podcastsKeyDown($event)">


The podcastKeyDown() function looks like this:



podcastsKeyDown(event) {
if(event.keyCode == 13) {
this.disableInput = true;
this.getUser(this.text).subscribe(account => {
this.disableInput = false;
this.isFocused = true;
});
}
}


When the user account has successfully returned i set the input field to be enabled, which works correctly. However the focus is not returned to this input. I have tried placing a timeout around re-setting the focus just in case there is some timing issue, however this did not work either. The code looked like this:



setTimeout(() => {
this.isPodcastNamesFocused = true;
}, 100);


Any ideas what is happening here and how to fix it?



Thanks in Advance.



EDIT 1: To be precise - it actually works the first time when using the timeout, but for subsequent user entries it does not...










share|improve this question

























  • Try with ngOnChanges(changes) { if (changes.isFocused.currentValue) ...

    – trichetriche
    Nov 16 '18 at 12:33











  • @trichetriche this did not work

    – Tom O'Brien
    Nov 16 '18 at 12:46














1












1








1








I have an input field that I want to disable when a user presses the 'enter' key. It will then try and fetch a user details. When it has fetched the details or there has been an error, I want to enable the input field again and set the focus on that field.



I am using this directive to set the focus on the input field:



import { Directive, OnChanges, ElementRef, Input } from '@angular/core';

@Directive({
selector: '[myFocus]'
})
export class FocusDirective implements OnChanges {

@Input('myFocus') isFocused: boolean;
constructor(private hostElement: ElementRef) { }

ngOnChanges() {
if(this.isFocused) {
this.hostElement.nativeElement.focus();
}
}
}


It is implemented in the html like so:



<input type="text" class="form-control" [(ngModel)]="text"
[myFocus]="isFocused" [disabled]="disableInput"
(keydown)="podcastsKeyDown($event)">


The podcastKeyDown() function looks like this:



podcastsKeyDown(event) {
if(event.keyCode == 13) {
this.disableInput = true;
this.getUser(this.text).subscribe(account => {
this.disableInput = false;
this.isFocused = true;
});
}
}


When the user account has successfully returned i set the input field to be enabled, which works correctly. However the focus is not returned to this input. I have tried placing a timeout around re-setting the focus just in case there is some timing issue, however this did not work either. The code looked like this:



setTimeout(() => {
this.isPodcastNamesFocused = true;
}, 100);


Any ideas what is happening here and how to fix it?



Thanks in Advance.



EDIT 1: To be precise - it actually works the first time when using the timeout, but for subsequent user entries it does not...










share|improve this question
















I have an input field that I want to disable when a user presses the 'enter' key. It will then try and fetch a user details. When it has fetched the details or there has been an error, I want to enable the input field again and set the focus on that field.



I am using this directive to set the focus on the input field:



import { Directive, OnChanges, ElementRef, Input } from '@angular/core';

@Directive({
selector: '[myFocus]'
})
export class FocusDirective implements OnChanges {

@Input('myFocus') isFocused: boolean;
constructor(private hostElement: ElementRef) { }

ngOnChanges() {
if(this.isFocused) {
this.hostElement.nativeElement.focus();
}
}
}


It is implemented in the html like so:



<input type="text" class="form-control" [(ngModel)]="text"
[myFocus]="isFocused" [disabled]="disableInput"
(keydown)="podcastsKeyDown($event)">


The podcastKeyDown() function looks like this:



podcastsKeyDown(event) {
if(event.keyCode == 13) {
this.disableInput = true;
this.getUser(this.text).subscribe(account => {
this.disableInput = false;
this.isFocused = true;
});
}
}


When the user account has successfully returned i set the input field to be enabled, which works correctly. However the focus is not returned to this input. I have tried placing a timeout around re-setting the focus just in case there is some timing issue, however this did not work either. The code looked like this:



setTimeout(() => {
this.isPodcastNamesFocused = true;
}, 100);


Any ideas what is happening here and how to fix it?



Thanks in Advance.



EDIT 1: To be precise - it actually works the first time when using the timeout, but for subsequent user entries it does not...







angular angular-directive






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 12:56







Tom O'Brien

















asked Nov 16 '18 at 12:26









Tom O'BrienTom O'Brien

48931948




48931948













  • Try with ngOnChanges(changes) { if (changes.isFocused.currentValue) ...

    – trichetriche
    Nov 16 '18 at 12:33











  • @trichetriche this did not work

    – Tom O'Brien
    Nov 16 '18 at 12:46



















  • Try with ngOnChanges(changes) { if (changes.isFocused.currentValue) ...

    – trichetriche
    Nov 16 '18 at 12:33











  • @trichetriche this did not work

    – Tom O'Brien
    Nov 16 '18 at 12:46

















Try with ngOnChanges(changes) { if (changes.isFocused.currentValue) ...

– trichetriche
Nov 16 '18 at 12:33





Try with ngOnChanges(changes) { if (changes.isFocused.currentValue) ...

– trichetriche
Nov 16 '18 at 12:33













@trichetriche this did not work

– Tom O'Brien
Nov 16 '18 at 12:46





@trichetriche this did not work

– Tom O'Brien
Nov 16 '18 at 12:46












3 Answers
3






active

oldest

votes


















1














I suggest the following solution. I tested this code locally. And it works every time for me.
Most of the code here is for demonstration.



Directive:



import {Directive, ElementRef, Input} from '@angular/core';

@Directive({
selector: '[myFocus]'
})
export class MyFocusDirective {
// as for me I prefer using setters for properties that have non-trivial logic when being set. They are simple, predictable and robust.
@Input('myFocus')
set isFocused(val: boolean) {
this._isFocused = val;
if (this._isFocused) {
this.hostElement.nativeElement.focus();
}
}
get isFocused(): boolean {
return this._isFocused;
}

_isFocused: boolean;
constructor(private hostElement: ElementRef) { }
}




Component:



import { Component } from '@angular/core';
import {Observable, of, timer} from 'rxjs';
import {map, take} from 'rxjs/operators';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
text = 'app';
isFocused: boolean = true;
isDisabled: boolean = false;
userData: {name: string, age: number} = null;

podcastsKeyDown(event) {
if (event.keyCode === 13) {
this.isFocused = false;
this.isDisabled = true;
// take(1) not to have subscriptions hanging around
this.getUser(this.text).pipe(take(1)).subscribe(account => {
this.isDisabled = false;
this.userData = account;
// timeout first makes DOM to render setting isDisabled to false
// when field is enabled we can make it focused
setTimeout(() => {
this.isFocused = true;
});
});
}
}

// some mock data
private getUser(name: string): Observable<{name: string, age: number}> {
return timer(2000).pipe(map(() => {
return {name, age: Math.round(Math.random() * 30 + 10)};
}));
}
}


<input type="text" class="form-control" [(ngModel)]="text"
[myFocus]="isFocused" [disabled]="isDisabled"
(keydown)="podcastsKeyDown($event)">
<p>{{account | json}}</p>







share|improve this answer

































    0














    It seems this was fixed by using the setTimeout() function AND remembering to set the focus to false while the user was being fetched. This must have been causing the focus directive to get confused.



    podcastsKeyDown(event) {
    if(event.keyCode == 13) {

    //This is the important line that was missing
    this.isFocused = false;

    this.disableInput = true;
    this.getUser(this.text).subscribe(account => {
    this.disableInput = false;
    setTimeout(() => {
    this.isFocused = true;
    });
    });
    }
    }





    share|improve this answer































      0














      ngOnChanges will work only if there is a pure change means if you have declared this.isFocused as true and you are trying to set it as true again ngOnChanges won't trigger



      Try something like this



      @Input('myFocus')
      set isFocused(value: boolean) {
      if (value) {
      this.hostElement.nativeElement.focus();
      }
      };


      or change your directive constructor like this constructor(@Host() @Self() private hostElement: ElementRef) { }



      Just got an idea - hope it works



      Try to pass the reference variable as an @Input() and read it



      <input type="text" class="form-control" [(ngModel)]="text" #inputType [element]="inputType"
      [myFocus]="isFocused" [disabled]="disableInput"
      (keydown)="podcastsKeyDown($event)">


      @Input('element') elementType : ElementRef;



      Try to focus the elementType now



      Hope it works - Happy coding !!






      share|improve this answer


























      • This did not work

        – Tom O'Brien
        Nov 16 '18 at 12:53











      • Try to do setTimeout(()=>this.hostElement.nativeElement.focus(),0); instead of doing it syncly

        – Aviad P.
        Nov 16 '18 at 12:58











      • @AviadP. The setTimeout in the directive did not work either - again it worked for the first user but not subsequent users - just like i mentioned about the timeout in the EDIT 1 comment

        – Tom O'Brien
        Nov 16 '18 at 13:07











      • Updated my answer

        – Rahul
        Nov 16 '18 at 14:48












      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53337898%2fangular-directive-not-setting-focus-properly-on-recently-disabled-input%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      I suggest the following solution. I tested this code locally. And it works every time for me.
      Most of the code here is for demonstration.



      Directive:



      import {Directive, ElementRef, Input} from '@angular/core';

      @Directive({
      selector: '[myFocus]'
      })
      export class MyFocusDirective {
      // as for me I prefer using setters for properties that have non-trivial logic when being set. They are simple, predictable and robust.
      @Input('myFocus')
      set isFocused(val: boolean) {
      this._isFocused = val;
      if (this._isFocused) {
      this.hostElement.nativeElement.focus();
      }
      }
      get isFocused(): boolean {
      return this._isFocused;
      }

      _isFocused: boolean;
      constructor(private hostElement: ElementRef) { }
      }




      Component:



      import { Component } from '@angular/core';
      import {Observable, of, timer} from 'rxjs';
      import {map, take} from 'rxjs/operators';

      @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
      })
      export class AppComponent {
      text = 'app';
      isFocused: boolean = true;
      isDisabled: boolean = false;
      userData: {name: string, age: number} = null;

      podcastsKeyDown(event) {
      if (event.keyCode === 13) {
      this.isFocused = false;
      this.isDisabled = true;
      // take(1) not to have subscriptions hanging around
      this.getUser(this.text).pipe(take(1)).subscribe(account => {
      this.isDisabled = false;
      this.userData = account;
      // timeout first makes DOM to render setting isDisabled to false
      // when field is enabled we can make it focused
      setTimeout(() => {
      this.isFocused = true;
      });
      });
      }
      }

      // some mock data
      private getUser(name: string): Observable<{name: string, age: number}> {
      return timer(2000).pipe(map(() => {
      return {name, age: Math.round(Math.random() * 30 + 10)};
      }));
      }
      }


      <input type="text" class="form-control" [(ngModel)]="text"
      [myFocus]="isFocused" [disabled]="isDisabled"
      (keydown)="podcastsKeyDown($event)">
      <p>{{account | json}}</p>







      share|improve this answer






























        1














        I suggest the following solution. I tested this code locally. And it works every time for me.
        Most of the code here is for demonstration.



        Directive:



        import {Directive, ElementRef, Input} from '@angular/core';

        @Directive({
        selector: '[myFocus]'
        })
        export class MyFocusDirective {
        // as for me I prefer using setters for properties that have non-trivial logic when being set. They are simple, predictable and robust.
        @Input('myFocus')
        set isFocused(val: boolean) {
        this._isFocused = val;
        if (this._isFocused) {
        this.hostElement.nativeElement.focus();
        }
        }
        get isFocused(): boolean {
        return this._isFocused;
        }

        _isFocused: boolean;
        constructor(private hostElement: ElementRef) { }
        }




        Component:



        import { Component } from '@angular/core';
        import {Observable, of, timer} from 'rxjs';
        import {map, take} from 'rxjs/operators';

        @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
        })
        export class AppComponent {
        text = 'app';
        isFocused: boolean = true;
        isDisabled: boolean = false;
        userData: {name: string, age: number} = null;

        podcastsKeyDown(event) {
        if (event.keyCode === 13) {
        this.isFocused = false;
        this.isDisabled = true;
        // take(1) not to have subscriptions hanging around
        this.getUser(this.text).pipe(take(1)).subscribe(account => {
        this.isDisabled = false;
        this.userData = account;
        // timeout first makes DOM to render setting isDisabled to false
        // when field is enabled we can make it focused
        setTimeout(() => {
        this.isFocused = true;
        });
        });
        }
        }

        // some mock data
        private getUser(name: string): Observable<{name: string, age: number}> {
        return timer(2000).pipe(map(() => {
        return {name, age: Math.round(Math.random() * 30 + 10)};
        }));
        }
        }


        <input type="text" class="form-control" [(ngModel)]="text"
        [myFocus]="isFocused" [disabled]="isDisabled"
        (keydown)="podcastsKeyDown($event)">
        <p>{{account | json}}</p>







        share|improve this answer




























          1












          1








          1







          I suggest the following solution. I tested this code locally. And it works every time for me.
          Most of the code here is for demonstration.



          Directive:



          import {Directive, ElementRef, Input} from '@angular/core';

          @Directive({
          selector: '[myFocus]'
          })
          export class MyFocusDirective {
          // as for me I prefer using setters for properties that have non-trivial logic when being set. They are simple, predictable and robust.
          @Input('myFocus')
          set isFocused(val: boolean) {
          this._isFocused = val;
          if (this._isFocused) {
          this.hostElement.nativeElement.focus();
          }
          }
          get isFocused(): boolean {
          return this._isFocused;
          }

          _isFocused: boolean;
          constructor(private hostElement: ElementRef) { }
          }




          Component:



          import { Component } from '@angular/core';
          import {Observable, of, timer} from 'rxjs';
          import {map, take} from 'rxjs/operators';

          @Component({
          selector: 'app-root',
          templateUrl: './app.component.html',
          styleUrls: ['./app.component.css']
          })
          export class AppComponent {
          text = 'app';
          isFocused: boolean = true;
          isDisabled: boolean = false;
          userData: {name: string, age: number} = null;

          podcastsKeyDown(event) {
          if (event.keyCode === 13) {
          this.isFocused = false;
          this.isDisabled = true;
          // take(1) not to have subscriptions hanging around
          this.getUser(this.text).pipe(take(1)).subscribe(account => {
          this.isDisabled = false;
          this.userData = account;
          // timeout first makes DOM to render setting isDisabled to false
          // when field is enabled we can make it focused
          setTimeout(() => {
          this.isFocused = true;
          });
          });
          }
          }

          // some mock data
          private getUser(name: string): Observable<{name: string, age: number}> {
          return timer(2000).pipe(map(() => {
          return {name, age: Math.round(Math.random() * 30 + 10)};
          }));
          }
          }


          <input type="text" class="form-control" [(ngModel)]="text"
          [myFocus]="isFocused" [disabled]="isDisabled"
          (keydown)="podcastsKeyDown($event)">
          <p>{{account | json}}</p>







          share|improve this answer















          I suggest the following solution. I tested this code locally. And it works every time for me.
          Most of the code here is for demonstration.



          Directive:



          import {Directive, ElementRef, Input} from '@angular/core';

          @Directive({
          selector: '[myFocus]'
          })
          export class MyFocusDirective {
          // as for me I prefer using setters for properties that have non-trivial logic when being set. They are simple, predictable and robust.
          @Input('myFocus')
          set isFocused(val: boolean) {
          this._isFocused = val;
          if (this._isFocused) {
          this.hostElement.nativeElement.focus();
          }
          }
          get isFocused(): boolean {
          return this._isFocused;
          }

          _isFocused: boolean;
          constructor(private hostElement: ElementRef) { }
          }




          Component:



          import { Component } from '@angular/core';
          import {Observable, of, timer} from 'rxjs';
          import {map, take} from 'rxjs/operators';

          @Component({
          selector: 'app-root',
          templateUrl: './app.component.html',
          styleUrls: ['./app.component.css']
          })
          export class AppComponent {
          text = 'app';
          isFocused: boolean = true;
          isDisabled: boolean = false;
          userData: {name: string, age: number} = null;

          podcastsKeyDown(event) {
          if (event.keyCode === 13) {
          this.isFocused = false;
          this.isDisabled = true;
          // take(1) not to have subscriptions hanging around
          this.getUser(this.text).pipe(take(1)).subscribe(account => {
          this.isDisabled = false;
          this.userData = account;
          // timeout first makes DOM to render setting isDisabled to false
          // when field is enabled we can make it focused
          setTimeout(() => {
          this.isFocused = true;
          });
          });
          }
          }

          // some mock data
          private getUser(name: string): Observable<{name: string, age: number}> {
          return timer(2000).pipe(map(() => {
          return {name, age: Math.round(Math.random() * 30 + 10)};
          }));
          }
          }


          <input type="text" class="form-control" [(ngModel)]="text"
          [myFocus]="isFocused" [disabled]="isDisabled"
          (keydown)="podcastsKeyDown($event)">
          <p>{{account | json}}</p>








          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 16 '18 at 14:02

























          answered Nov 16 '18 at 13:55









          Daniil Andreyevich BaunovDaniil Andreyevich Baunov

          1,137528




          1,137528

























              0














              It seems this was fixed by using the setTimeout() function AND remembering to set the focus to false while the user was being fetched. This must have been causing the focus directive to get confused.



              podcastsKeyDown(event) {
              if(event.keyCode == 13) {

              //This is the important line that was missing
              this.isFocused = false;

              this.disableInput = true;
              this.getUser(this.text).subscribe(account => {
              this.disableInput = false;
              setTimeout(() => {
              this.isFocused = true;
              });
              });
              }
              }





              share|improve this answer




























                0














                It seems this was fixed by using the setTimeout() function AND remembering to set the focus to false while the user was being fetched. This must have been causing the focus directive to get confused.



                podcastsKeyDown(event) {
                if(event.keyCode == 13) {

                //This is the important line that was missing
                this.isFocused = false;

                this.disableInput = true;
                this.getUser(this.text).subscribe(account => {
                this.disableInput = false;
                setTimeout(() => {
                this.isFocused = true;
                });
                });
                }
                }





                share|improve this answer


























                  0












                  0








                  0







                  It seems this was fixed by using the setTimeout() function AND remembering to set the focus to false while the user was being fetched. This must have been causing the focus directive to get confused.



                  podcastsKeyDown(event) {
                  if(event.keyCode == 13) {

                  //This is the important line that was missing
                  this.isFocused = false;

                  this.disableInput = true;
                  this.getUser(this.text).subscribe(account => {
                  this.disableInput = false;
                  setTimeout(() => {
                  this.isFocused = true;
                  });
                  });
                  }
                  }





                  share|improve this answer













                  It seems this was fixed by using the setTimeout() function AND remembering to set the focus to false while the user was being fetched. This must have been causing the focus directive to get confused.



                  podcastsKeyDown(event) {
                  if(event.keyCode == 13) {

                  //This is the important line that was missing
                  this.isFocused = false;

                  this.disableInput = true;
                  this.getUser(this.text).subscribe(account => {
                  this.disableInput = false;
                  setTimeout(() => {
                  this.isFocused = true;
                  });
                  });
                  }
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 16 '18 at 14:45









                  Tom O'BrienTom O'Brien

                  48931948




                  48931948























                      0














                      ngOnChanges will work only if there is a pure change means if you have declared this.isFocused as true and you are trying to set it as true again ngOnChanges won't trigger



                      Try something like this



                      @Input('myFocus')
                      set isFocused(value: boolean) {
                      if (value) {
                      this.hostElement.nativeElement.focus();
                      }
                      };


                      or change your directive constructor like this constructor(@Host() @Self() private hostElement: ElementRef) { }



                      Just got an idea - hope it works



                      Try to pass the reference variable as an @Input() and read it



                      <input type="text" class="form-control" [(ngModel)]="text" #inputType [element]="inputType"
                      [myFocus]="isFocused" [disabled]="disableInput"
                      (keydown)="podcastsKeyDown($event)">


                      @Input('element') elementType : ElementRef;



                      Try to focus the elementType now



                      Hope it works - Happy coding !!






                      share|improve this answer


























                      • This did not work

                        – Tom O'Brien
                        Nov 16 '18 at 12:53











                      • Try to do setTimeout(()=>this.hostElement.nativeElement.focus(),0); instead of doing it syncly

                        – Aviad P.
                        Nov 16 '18 at 12:58











                      • @AviadP. The setTimeout in the directive did not work either - again it worked for the first user but not subsequent users - just like i mentioned about the timeout in the EDIT 1 comment

                        – Tom O'Brien
                        Nov 16 '18 at 13:07











                      • Updated my answer

                        – Rahul
                        Nov 16 '18 at 14:48
















                      0














                      ngOnChanges will work only if there is a pure change means if you have declared this.isFocused as true and you are trying to set it as true again ngOnChanges won't trigger



                      Try something like this



                      @Input('myFocus')
                      set isFocused(value: boolean) {
                      if (value) {
                      this.hostElement.nativeElement.focus();
                      }
                      };


                      or change your directive constructor like this constructor(@Host() @Self() private hostElement: ElementRef) { }



                      Just got an idea - hope it works



                      Try to pass the reference variable as an @Input() and read it



                      <input type="text" class="form-control" [(ngModel)]="text" #inputType [element]="inputType"
                      [myFocus]="isFocused" [disabled]="disableInput"
                      (keydown)="podcastsKeyDown($event)">


                      @Input('element') elementType : ElementRef;



                      Try to focus the elementType now



                      Hope it works - Happy coding !!






                      share|improve this answer


























                      • This did not work

                        – Tom O'Brien
                        Nov 16 '18 at 12:53











                      • Try to do setTimeout(()=>this.hostElement.nativeElement.focus(),0); instead of doing it syncly

                        – Aviad P.
                        Nov 16 '18 at 12:58











                      • @AviadP. The setTimeout in the directive did not work either - again it worked for the first user but not subsequent users - just like i mentioned about the timeout in the EDIT 1 comment

                        – Tom O'Brien
                        Nov 16 '18 at 13:07











                      • Updated my answer

                        – Rahul
                        Nov 16 '18 at 14:48














                      0












                      0








                      0







                      ngOnChanges will work only if there is a pure change means if you have declared this.isFocused as true and you are trying to set it as true again ngOnChanges won't trigger



                      Try something like this



                      @Input('myFocus')
                      set isFocused(value: boolean) {
                      if (value) {
                      this.hostElement.nativeElement.focus();
                      }
                      };


                      or change your directive constructor like this constructor(@Host() @Self() private hostElement: ElementRef) { }



                      Just got an idea - hope it works



                      Try to pass the reference variable as an @Input() and read it



                      <input type="text" class="form-control" [(ngModel)]="text" #inputType [element]="inputType"
                      [myFocus]="isFocused" [disabled]="disableInput"
                      (keydown)="podcastsKeyDown($event)">


                      @Input('element') elementType : ElementRef;



                      Try to focus the elementType now



                      Hope it works - Happy coding !!






                      share|improve this answer















                      ngOnChanges will work only if there is a pure change means if you have declared this.isFocused as true and you are trying to set it as true again ngOnChanges won't trigger



                      Try something like this



                      @Input('myFocus')
                      set isFocused(value: boolean) {
                      if (value) {
                      this.hostElement.nativeElement.focus();
                      }
                      };


                      or change your directive constructor like this constructor(@Host() @Self() private hostElement: ElementRef) { }



                      Just got an idea - hope it works



                      Try to pass the reference variable as an @Input() and read it



                      <input type="text" class="form-control" [(ngModel)]="text" #inputType [element]="inputType"
                      [myFocus]="isFocused" [disabled]="disableInput"
                      (keydown)="podcastsKeyDown($event)">


                      @Input('element') elementType : ElementRef;



                      Try to focus the elementType now



                      Hope it works - Happy coding !!







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 16 '18 at 14:48

























                      answered Nov 16 '18 at 12:43









                      RahulRahul

                      1,1492319




                      1,1492319













                      • This did not work

                        – Tom O'Brien
                        Nov 16 '18 at 12:53











                      • Try to do setTimeout(()=>this.hostElement.nativeElement.focus(),0); instead of doing it syncly

                        – Aviad P.
                        Nov 16 '18 at 12:58











                      • @AviadP. The setTimeout in the directive did not work either - again it worked for the first user but not subsequent users - just like i mentioned about the timeout in the EDIT 1 comment

                        – Tom O'Brien
                        Nov 16 '18 at 13:07











                      • Updated my answer

                        – Rahul
                        Nov 16 '18 at 14:48



















                      • This did not work

                        – Tom O'Brien
                        Nov 16 '18 at 12:53











                      • Try to do setTimeout(()=>this.hostElement.nativeElement.focus(),0); instead of doing it syncly

                        – Aviad P.
                        Nov 16 '18 at 12:58











                      • @AviadP. The setTimeout in the directive did not work either - again it worked for the first user but not subsequent users - just like i mentioned about the timeout in the EDIT 1 comment

                        – Tom O'Brien
                        Nov 16 '18 at 13:07











                      • Updated my answer

                        – Rahul
                        Nov 16 '18 at 14:48

















                      This did not work

                      – Tom O'Brien
                      Nov 16 '18 at 12:53





                      This did not work

                      – Tom O'Brien
                      Nov 16 '18 at 12:53













                      Try to do setTimeout(()=>this.hostElement.nativeElement.focus(),0); instead of doing it syncly

                      – Aviad P.
                      Nov 16 '18 at 12:58





                      Try to do setTimeout(()=>this.hostElement.nativeElement.focus(),0); instead of doing it syncly

                      – Aviad P.
                      Nov 16 '18 at 12:58













                      @AviadP. The setTimeout in the directive did not work either - again it worked for the first user but not subsequent users - just like i mentioned about the timeout in the EDIT 1 comment

                      – Tom O'Brien
                      Nov 16 '18 at 13:07





                      @AviadP. The setTimeout in the directive did not work either - again it worked for the first user but not subsequent users - just like i mentioned about the timeout in the EDIT 1 comment

                      – Tom O'Brien
                      Nov 16 '18 at 13:07













                      Updated my answer

                      – Rahul
                      Nov 16 '18 at 14:48





                      Updated my answer

                      – Rahul
                      Nov 16 '18 at 14:48


















                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53337898%2fangular-directive-not-setting-focus-properly-on-recently-disabled-input%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Bressuire

                      Vorschmack

                      Quarantine