admin管理员组

文章数量:1332865

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

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

Share Improve this question asked Apr 20, 2018 at 18:37 nicknick 3,7113 gold badges25 silver badges34 bronze badges 5
  • Is there a reason you can't attach the blur in your markup? <input (blur)="blurHandler()" /> Here is a great link for reference: stackoverflow./questions/34918198/… – Pearman Commented Apr 20, 2018 at 18:45
  • 1 @Pearman that's good for handle blur events, I actually want to trigger one – nick Commented Apr 20, 2018 at 18:48
  • Can you show the context where you call this.searchInput.nativeElement.blur()? – Martin Parenteau Commented Apr 20, 2018 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. – Martin Parenteau Commented Apr 20, 2018 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 below ! codecraft.tv/courses/angular/custom-directives/… – Gustavo Cirulo Commented Jan 15, 2019 at 12:45
Add a ment  | 

3 Answers 3

Reset to default 5

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

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

this.renderer.invokeElementMethod(this.searchInput.nativeElement, 'blur', []);

The correct answer is to use

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

本文标签: javascriptAngular blur inputStack Overflow