nick
nick

Reputation: 3711

Angular blur input

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

Upvotes: 3

Views: 4975

Answers (3)

Co ti
Co ti

Reputation: 144

The correct answer is to use

this.renderer.selectRootElement(nativeElement).dispatchEvent(new Event('blur'));

Upvotes: 0

mtpultz
mtpultz

Reputation: 18268

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();
}

Upvotes: 5

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

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', []);

Upvotes: 2

Related Questions