Autofocus doesn’t work in modals

Feature description:

I’ve got an input in my modal. I’d like it to autofocus when the modal opens. I’ve added the autofocus attribute and this works the first time the modal is opened in Google Chrome, but not subsequently. It doesn’t seem to work at all in Safari. I haven’t tested other browsers.

As a workaround, I’ve created an attribute directive that focuses the input during ngAfterViewInit, but this seems like using a sledge hammer to crack a nut (and it could create unexpected behaviour elsewhere.)

Link to minimally-working plunker that reproduces the issue:

http://plnkr.co/edit/At2FNwl9lKGF3sk2gTbt?p=preview

Version of Angular, ng-bootstrap, and Bootstrap:

Angular: v2.0.1

ng-bootstrap: v1.0.0-alpha.5

Bootstrap: v4.0.0-alpha.4

1 possible answer(s) on “Autofocus doesn’t work in modals

  1. Solution to this is rather simple. Your own focus directive. I even do not understand why this directive is not default in Angular core.

    http://plnkr.co/edit/2euC1MDHup7x4ShJcXQl?p=preview

    import { Directive, Input, ElementRef } from '@angular/core';
    
    @Directive({
    	selector : '[focus]'
    })
    export class FocusDirective {
    	@Input()
    	focus : boolean;
    
    	constructor(private element : ElementRef) {
    	}
    
    	protected ngOnChanges() {
    		if (this.focus)
    			this.element.nativeElement.focus();
    	}
    }