2

I'd like to "blur" (or unfocus, etc.) an input element from a controller.

I have reference to the input @ViewChild('searchInput') searchInput: ElementRef

This works:

this.searchInput.nativeElement.focus()

But this doesn't appear to:

this.searchInput.nativeElement.blur()

nick
  • 3,521
  • 3
  • 22
  • 32
  • Is there a reason you can't attach the blur in your markup? `` Here is a great link for reference: https://stackoverflow.com/questions/34918198/how-to-use-onblur-event-on-angular2?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Pearman Apr 20 '18 at 18:45
  • 1
    @Pearman that's good for handle blur events, I actually want to trigger one – nick Apr 20 '18 at 18:48
  • Can you show the context where you call `this.searchInput.nativeElement.blur()`? – ConnorsFan Apr 20 '18 at 19:32
  • 1
    Your code should work, as long as it is called when the element is present in the DOM. See [this stackblitz](https://stackblitz.com/edit/angular-wxenxn). – ConnorsFan Apr 20 '18 at 19:40
  • If you want to make one way that you can use in all inputs fields in your solution you can use Decorator @HostListener ('mouseout'). You can see more about this in this [Link](https://codecraft.tv/courses/angular/custom-directives/hostlistener-and-hostbinding/ "@HostListener and @HostBinding") below ! https://codecraft.tv/courses/angular/custom-directives/hostlistener-and-hostbinding/ – Gustavo Cirulo Jan 15 '19 at 12:45

3 Answers3

4

In Angular 5+ Renderer has been deprecated, and Renderer2 doesn't have the invokeElementMethod, but your example should work. The only thing I can think of without seeing more of your code is you didn't add the template reference to your input in the markup:

Template

<input #myInput id="example" name="example" formControlName="example ...>

Controller

@ViewChild('myInput') public myInput: ElementRef<HTMLElement>;

// ...

public onSubmit() {
  this.myInput.nativeElement.blur();
}
mtpultz
  • 17,267
  • 22
  • 122
  • 201
2

Can try using Renderer, Inject Renderer in your component and call the code below when you want to blur

this.renderer.invokeElementMethod(this.searchInput.nativeElement, 'blur', []);
Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51
0

The correct answer is to use

this.renderer.selectRootElement(nativeElement).dispatchEvent(new Event('blur'));
Co ti
  • 124
  • 2
  • 13