229

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

16 Answers 16

246

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);  
}
Sign up to request clarification or add additional context in comments.

13 Comments

Why do we need to use setTimeout? Isn't the change of boolean synchronous?
doesn't that mess with zonejs?
This works, but without a clear explanation it's magic. Magic breaks often.
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.
setTimeout refreshes all the layout even it is in onPush. Better to trigger this.cdr.detectChanges() instead of setTImeout.
|
77

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 Comments

This will only work once every page refresh, not multiple times.
Works with a mutation observer, as the html5 spec intended. :)
got the error Property 'querySelectorAll' does not exist on type 'Node'.ts(2339)
@norca, this is probably related to your use in TypeScript. The solution is probably to cast the node to element type on line 6.
53

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 Comments

thank you, this is the only solusion that worked for me in the case of waiting on http request
I find this solution more preferrable than the accepted answer. It's cleaner in the case of code reuse, and more Angular-centric.
Also don't forget to add directive in module's declarations.
Similar answer with an even simpler Renderer2 alternative.
The solution works fine for Angular 4, just requires to wrap setting of focus and selection with setTimeout function. Thx!
48

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'

4 Comments

Best solution. Thanks. Other solutions gave me error.
Great solution - Works well and is Pain-free.
Yes, this is the way to do it in 2022!
Unfortunately, this method holds the focus on the input and the User cannot move on to other inputs by pressing the TAB key...
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 Comments

This seems to be pretty much identical to the accepted answer
best solution, but focused must not be private
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 Comments

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 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.
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 Comments

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!
Didn't work for me. I get ERROR TypeError: Cannot read property 'focus' of undefined
@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)
Same answer of Sandipan Mitra
if element is inside ngFor , this solution has error : Property 'myInput' does not exist on type 'myComponent' !!!
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 Comments

I tried this with angular 7, it did not work, using timeout worked fine
for me also in angular 8 is not working, to bad we have to go back to setTimeout
working fine, set instead of setTimeout due to full refresh of page by setTimeout affecting.
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 Comment

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).
7

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

Comments

4

Only using Angular Template

<input type="text" #searchText>

<span (click)="searchText.focus()">clear</span>

3 Comments

"If you're using Material..."
ERROR TypeError: Cannot read property 'focus' of undefined
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...
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>

Comments

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.

Comments

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

        this.inputField.nativeElement.focus();

        }

this will auto focus on '#input1' element.

Comments

1

Umut Esen authored an excellent short article on this topic that addresses the problem effectively using Renderer2. Read it here: https://onthecode.co.uk/blog/angular-material-focus-form-input-with-renderer2

He explains this overcomes problems with both Security and Separation of Concerns.

A bit of his code follows:

constructor(private renderer: Renderer2) {}

focusMyInput() {
  this.renderer.selectRootElement('#myInput').focus();
}

Comments

-1

Easier way is also to do this.

let elementReference = document.querySelector('<your css, #id selector>');
    if (elementReference instanceof HTMLElement) {
        elementReference.focus();
    }

1 Comment

You really don't want to query the dom directly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.