218

I am working a front-end application with Angular 5, and I need to have a search box hidden, but on click of a button, the search box should be displayed and focused.

I have tried a few ways found on StackOverflow with directive or so, but can't succeed.

Here is the sample code:

@Component({
   selector: 'my-app',
   template: `
    <div>
    <h2>Hello</h2>
    </div>
    <button (click) ="showSearch()">Show Search</button>
    <p></p>
    <form>
      <div >
        <input *ngIf="show" #search type="text"  />            
      </div>
    </form>
    `,
  })
  export class App implements AfterViewInit {
  @ViewChild('search') searchElement: ElementRef;

  show: false;
  name:string;
  constructor() {    
  }

  showSearch(){
    this.show = !this.show;    
    this.searchElement.nativeElement.focus();
    alert("focus");
  }

  ngAfterViewInit() {
    this.firstNameElement.nativeElement.focus();
  }

The search box is not set to focus.

How can I do that?

0

15 Answers 15

240

Edit 2022:
Read a more modern way with @Cichy's answer below


Modify the show search method like this

showSearch(){
  this.show = !this.show;  
  setTimeout(()=>{ // this will make the execution after the above boolean has changed
    this.searchElement.nativeElement.focus();
  },0);  
}
12
  • 25
    Why do we need to use setTimeout? Isn't the change of boolean synchronous? Commented May 2, 2019 at 17:40
  • 6
    doesn't that mess with zonejs?
    – Laurence
    Commented May 6, 2019 at 21:08
  • 34
    This works, but without a clear explanation it's magic. Magic breaks often.
    – John White
    Commented Apr 25, 2020 at 3:40
  • 8
    tl;dr: using setTimeout makes your code async, by adding a function execution to the event loop, and triggering change detection a second time when it executes. It does have a performance hit.
    – hevans900
    Commented Sep 3, 2020 at 9:11
  • 5
    setTimeout refreshes all the layout even it is in onPush. Better to trigger this.cdr.detectChanges() instead of setTImeout. Commented Apr 23, 2021 at 19:28
72

You should use HTML autofocus for this:

<input *ngIf="show" #search type="text" autofocus /> 

Note: if your component is persisted and reused, it will only autofocus the first time the fragment is attached. This can be overcome by having a global DOM listener that checks for autofocus attribute inside a DOM fragment when it is attached and then reapplying it or focus via JavaScript.

Here is an example global listener, it only needs to be placed in your spa application once and autofocus will function regardless of how many times the same fragment is reused:

(new MutationObserver(function (mutations, observer) {
    for (let i = 0; i < mutations.length; i++) {
        const m = mutations[i];
        if (m.type == 'childList') {
            for (let k = 0; k < m.addedNodes.length; k++) {
                const autofocuses = m.addedNodes[k].querySelectorAll("[autofocus]"); //Note: this ignores the fragment's root element
                console.log(autofocuses);
                if (autofocuses.length) {
                    const a = autofocuses[autofocuses.length - 1]; // focus last autofocus element
                    a.focus();
                    a.select();
                }
            }
        }
    }
})).observe(document.body, { attributes: false, childList: true, subtree: true });
4
  • 83
    This will only work once every page refresh, not multiple times.
    – moritzg
    Commented Jan 2, 2019 at 9:57
  • 1
    Works with a mutation observer, as the html5 spec intended. :)
    – N-ate
    Commented Apr 8, 2022 at 15:13
  • got the error Property 'querySelectorAll' does not exist on type 'Node'.ts(2339)
    – norca
    Commented Oct 19, 2022 at 10:51
  • @norca, this is probably related to your use in TypeScript. The solution is probably to cast the node to element type on line 6.
    – N-ate
    Commented Oct 19, 2022 at 17:10
51

This directive will instantly focus and select any text in the element as soon as it's displayed. This might require a setTimeout for some cases, it has not been tested much.

import { Directive, ElementRef, OnInit } from '@angular/core';
    
@Directive({
  selector: '[appPrefixFocusAndSelect]',
})
export class FocusOnShowDirective implements OnInit {    
  constructor(private el: ElementRef) {
    if (!el.nativeElement['focus']) {
      throw new Error('Element does not accept focus.');
    }
  }
    
  ngOnInit(): void {
    const input: HTMLInputElement = this.el.nativeElement as HTMLInputElement;
    input.focus();
    input.select();
  }
}

And in the HTML:

<mat-form-field>
  <input matInput type="text" appPrefixFocusAndSelect [value]="'etc'">
</mat-form-field>
5
  • thank you, this is the only solusion that worked for me in the case of waiting on http request Commented Mar 26, 2020 at 10:15
  • 3
    I find this solution more preferrable than the accepted answer. It's cleaner in the case of code reuse, and more Angular-centric. Commented Jul 6, 2020 at 14:09
  • Also don't forget to add directive in module's declarations. Commented Nov 26, 2020 at 11:55
  • Similar answer with an even simpler Renderer2 alternative.
    – hlovdal
    Commented Feb 28, 2021 at 12:29
  • The solution works fine for Angular 4, just requires to wrap setting of focus and selection with setTimeout function. Thx!
    – KEMBL
    Commented Jul 6, 2021 at 14:15
44

html of component:

<input [cdkTrapFocusAutoCapture]="show" [cdkTrapFocus]="show">

controler of component:

showSearch() {
  this.show = !this.show;    
}

..and do not forget about import A11yModule from @angular/cdk/a11y

import { A11yModule } from '@angular/cdk/a11y'
3
  • 5
    Best solution. Thanks. Other solutions gave me error.
    – Reza Taba
    Commented Jan 7, 2021 at 0:46
  • 3
    Great solution - Works well and is Pain-free. Commented Aug 6, 2021 at 5:53
  • 5
    Yes, this is the way to do it in 2022!
    – Shadoweb
    Commented Aug 13, 2022 at 14:20
21

I'm going to weigh in on this (Angular 7 Solution)

input [appFocus]="focus"....
import {AfterViewInit, Directive, ElementRef, Input,} from '@angular/core';

@Directive({
  selector: 'input[appFocus]',
})
export class FocusDirective implements AfterViewInit {

  @Input('appFocus')
  private focused: boolean = false;

  constructor(public element: ElementRef<HTMLElement>) {
  }

  ngAfterViewInit(): void {
    // ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.
    if (this.focused) {
      setTimeout(() => this.element.nativeElement.focus(), 0);
    }
  }
}
2
  • 2
    This seems to be pretty much identical to the accepted answer
    – Liam
    Commented Jul 21, 2020 at 15:05
  • best solution, but focused must not be private
    – Galdor
    Commented Dec 9, 2021 at 15:11
17

This is working i Angular 8 without setTimeout:

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

@Directive({
  selector: 'input[inputAutoFocus]'
})
export class InputFocusDirective implements AfterContentChecked {
  constructor(private element: ElementRef<HTMLInputElement>) {}

  ngAfterContentChecked(): void {
    this.element.nativeElement.focus();
  }
}

Explanation: Ok so this works because of: Change detection. It's the same reason that setTimout works, but when running a setTimeout in Angular it will bypass Zone.js and run all checks again, and it works because when the setTimeout is complete all changes are completed. With the correct lifecycle hook (AfterContentChecked) the same result can be be reached, but with the advantage that the extra cycle won't be run. The function will fire when all changes are checked and passed, and runs after the hooks AfterContentInit and DoCheck. If i'm wrong here please correct me.

More one lifecycles and change detection on https://angular.io/guide/lifecycle-hooks

UPDATE: I found an even better way to do this if one is using Angular Material CDK, the a11y-package. First import A11yModule in the the module declaring the component you have the input-field in. Then use cdkTrapFocus and cdkTrapFocusAutoCapture directives and use like this in html and set tabIndex on the input:

<div class="dropdown" cdkTrapFocus cdkTrapFocusAutoCapture>
    <input type="text tabIndex="0">
</div>

We had some issues with our dropdowns regarding positioning and responsiveness and started using the OverlayModule from the cdk instead, and this method using A11yModule works flawlessly.

2
  • Hi...I don't try cdkTrapFocusAutoCapture attribute, but I changed your first example into my code. For reasons unknown (for me) it did not work with AfterContentChecked lifecycle hook, but only with OnInit. In particolar with AfterContentChecked I can't change focus and move (with mouse or keyoboard) onto another input without that directive in the same form.
    – timhecker
    Commented Jul 6, 2020 at 13:47
  • @timhecker yeah we faced a similiar issue when migration our components to the cdk overlay (it worked when using just css instead of an overlay for positioning). It focused indefinitely on the input when a component using the directive was visible. Only solution I found was to use the cdk directives mentioned in the update.
    – SNDVLL
    Commented Aug 17, 2020 at 6:16
16

In Angular, within HTML itself, you can set focus to input on click of a button.

<button (click)="myInput.focus()">Click Me</button>

<input #myInput></input>
5
  • 1
    This answer shows a simple way to programmatically select another element in HTML, which is what I was looking for (all the "initial focus" answers don't solve how to react to an event by changing focus) - unfortunately, I needed to react to a mat-select selectionChanged event that happens before other UI stuff, so pulling the focus at that point didn't work. Instead I had to write a method setFocus(el:HTMLElement):void { setTimeout(()=>el.focus(),0); } and call it from the event handler: <mat-select (selectionChanged)="setFocus(myInput)">. Not as nice, but simple and works well. thx!
    – Guss
    Commented Aug 19, 2020 at 11:58
  • Didn't work for me. I get ERROR TypeError: Cannot read property 'focus' of undefined
    – Reza Taba
    Commented Jan 7, 2021 at 0:52
  • @RezaTaba, did you call the function 'myInput.focus()' or you just wrote 'myInput.focus' ? Also, make sure, your input element is inside a rendered div (*ngIf false can cause error, for example) Commented Jan 7, 2021 at 11:10
  • Same answer of Sandipan Mitra Commented Jun 28, 2021 at 16:06
  • if element is inside ngFor , this solution has error : Property 'myInput' does not exist on type 'myComponent' !!! Commented Oct 9, 2023 at 11:34
12

To make the execution after the boolean has changed and avoid the usage of timeout you can do:

import { ChangeDetectorRef } from '@angular/core';

constructor(private cd: ChangeDetectorRef) {}

showSearch(){
  this.show = !this.show;  
  this.cd.detectChanges();
  this.searchElement.nativeElement.focus();
}
3
  • 5
    I tried this with angular 7, it did not work, using timeout worked fine
    – rekiem87
    Commented Jan 18, 2019 at 6:44
  • for me also in angular 8 is not working, to bad we have to go back to setTimeout Commented Nov 6, 2019 at 8:36
  • working fine, set instead of setTimeout due to full refresh of page by setTimeout affecting. Commented Apr 23, 2021 at 19:29
9

I'm having same scenario, this worked for me but i'm not having the "hide/show" feature you have. So perhaps you could first check if you get the focus when you have the field always visible, and then try to solve why does not work when you change visibility (probably that's why you need to apply a sleep or a promise)

To set focus, this is the only change you need to do:

your Html mat input should be:

<input #yourControlName matInput>

in your TS class, reference like this in the variables section (

export class blabla...
    @ViewChild("yourControlName") yourControl : ElementRef;

Your button it's fine, calling:

  showSearch(){
       ///blabla... then finally:
       this.yourControl.nativeElement.focus();
}

and that's it. You can check this solution on this post that I found, so thanks to --> https://codeburst.io/focusing-on-form-elements-the-angular-way-e9a78725c04f

1
  • This worked well for my use case: I needed to show an input box if the user selected a specific option in a menu, and I wanted it to achieve focus only in that scenario (not automatically, after the component was initialized, which is what autofocus did).
    – Todd
    Commented Dec 23, 2021 at 4:42
6

There is also a DOM attribute called cdkFocusInitial which works for me on inputs. You can read more about it here: https://material.angular.io/cdk/a11y/overview

0
4

Only using Angular Template

<input type="text" #searchText>

<span (click)="searchText.focus()">clear</span>
3
  • "If you're using Material..." Commented Nov 11, 2020 at 19:59
  • 3
    ERROR TypeError: Cannot read property 'focus' of undefined
    – Reza Taba
    Commented Jan 7, 2021 at 0:53
  • This only works if input element comes b4 the click element which is not my case it didn't work Property 'searchText' does not exist on type... Commented Nov 5, 2021 at 14:09
2

When using an overlay/dialog, you need to use cdkFocusInitial within cdkTrapFocus and cdkTrapFocusAutoCapture.

CDK Regions:

If you're using cdkFocusInitial together with the CdkTrapFocus directive, nothing will happen unless you've enabled the cdkTrapFocusAutoCapture option as well. This is due to CdkTrapFocus not capturing focus on initialization by default.

In the overlay/dialog component:

<div cdkTrapFocus cdkTrapFocusAutoCapture>
  <input cdkFocusInitial>
</div>
1

@john-white The reason the magic works with a zero setTimeout is because

this.searchElement.nativeElement.focus();

is sent to the end of the browser callStack and therefore executed last/later, its not a very nice way of getting it to work and it probably means there is other logic in the code that could be improved on.

1
@ViewChild("input1") inputField: ElementRef;
  
 ngAfterViewInit() {

        this.inputField.nativeElement.focus();

        }

this will auto focus on '#input1' element.

-1

Easier way is also to do this.

let elementReference = document.querySelector('<your css, #id selector>');
    if (elementReference instanceof HTMLElement) {
        elementReference.focus();
    }
1
  • 4
    You really don't want to query the dom directly. Commented Jun 19, 2020 at 17:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.