View Answer

This is my current code:

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

@Directive({
    selector: "[autofocus]"
})
export class AutofocusDirective
{
    private focus = true;

    constructor(private el: ElementRef)
    {
    }

    ngOnInit()
    {
        if (this.focus)
        {
            //Otherwise Angular throws error: Expression has changed after it was checked.
            window.setTimeout(() =>
            {
                this.el.nativeElement.focus(); //For SSR (server side rendering) this is not safe. Use: https://github.com/angular/angular/issues/15008#issuecomment-285141070)
            });
        }
    }

    @Input() set autofocus(condition: boolean)
    {
        this.focus = condition !== false;
    }
}

use case:

[autofocus] //will focus
[autofocus]="true" //will focus
[autofocus]="false" //will not focus

Outdated code (old answer, just in case):
I ended up with this code:

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

@Directive({
    selector: '[autofocus]'
})
export class Autofocus
{
    constructor(private el: ElementRef, private renderer: Renderer)
    {        
    }

    ngOnInit()
    {        
    }

    ngAfterViewInit()
    {
        this.renderer.invokeElementMethod(this.el.nativeElement, 'focus', []);
    }
}

If I put code in ngOnViewInit it does not work. Code also use best practices, since calling focus on element directly is not recommended.

Edited (conditional autofocus):
A few days ago I needed conditional auto focus, because I hide first autofocus element and I want to focus another, but only when first is not visible, and I ended with this code:

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

@Directive({
    selector: '[autofocus]'
})
export class AutofocusDirective
{
    private _autofocus;
    constructor(private el: ElementRef, private renderer: Renderer)
    {
    }

    ngOnInit()
    {
    }

    ngAfterViewInit()
    {
        if (this._autofocus || typeof this._autofocus === "undefined")
            this.renderer.invokeElementMethod(this.el.nativeElement, 'focus', []);
    }

    @Input() set autofocus(condition: boolean)
    {
        this._autofocus = condition != false;
    }
}

Edited2:
Renderer.invokeElementMethod is deprecated and new Renderer2 does not support it. So we are back to native focus (which doesn't work outside DOM - SSR for example!).

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

@Directive({
    selector: '[autofocus]'
})
export class AutofocusDirective
{
    private _autofocus;
    constructor(private el: ElementRef)
    {
    }

    ngOnInit()
    {
        if (this._autofocus || typeof this._autofocus === "undefined")
            this.el.nativeElement.focus();      //For SSR (server side rendering) this is not safe. Use: https://github.com/angular/angular/issues/15008#issuecomment-285141070)
    }

    @Input() set autofocus(condition: boolean)
    {
        this._autofocus = condition != false;
    }
}

use case:

[autofocus] //will focus
[autofocus]="true" //will focus
[autofocus]="false" //will not focus
Score: 86
Comments: 11
Date posted: 3/12/2017

View Answer

ngFocus is not what you're looking for. That directive is more of an event trigger. It will execute your code whenever the user gives focus to the textbox.

What you want is something like this custom directive:

angular
    .module('myApp')
    .directive('autofocus', function($timeout) {
        return {
            link: function(scope, element, attrs) {
                $timeout(function() {
                    element.focus();
                });
            }
        }
    });

Inspired by http://ericclemmons.com/angular/angular-autofocus-directive/

Score: 9
Comments: 2
Date posted: 4/29/2015

View Answer

To solve the issue of "Autofocus only working on page refresh"

Do the following changes in your files:-

//In module.ts file 

import { AutofocusModule } from 'angular-autofocus-fix';

@NgModule({
imports: [
AutofocusModule
],

//In package.json file add the dependencies as:- 

    "dependencies": {
    "angular-autofocus-fix": "^0.1.0"
}
Score: 3
Comments: 0
Date posted: 7/9/2018

View Answer
Score: 0
Comments: 2
Date posted: 1/24/2020

View Answer

run npm install angular-autofocus-fix --save in cli

import import { AutofocusModule } from 'angular-autofocus-fix'; in your module and AutofocusModule in import section.

then you can freely use autofocus as an attribute in any tag.

or

use autofocus="true" in input tag, see updated snippet

<div>
<input autofocus="true" type="text" name="fname"><br>
<myDropdownComp > </myDropdownComp>
</div>

Score: 0
Comments: 0
Date posted: 9/21/2018


1


© 2021 Search Overflow
Contributions licensed under cc by-sa