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()
-
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
3 Answers
Reset to default 5In 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
版权声明:本文标题:javascript - Angular blur input - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742287019a2447108.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论