Angular 2专注于Click/Event之后的第一个无效输入 [英] Angular 2 Focus on first invalid input after Click/Event
问题描述
我有一个奇怪的要求,希望能有所帮助.
I have an odd requirement and was hoping for some help.
我需要关注单击按钮(未提交)后首次发现表单的无效输入.表单很大,因此屏幕需要滚动到第一个无效输入.
I need to focus on the first found invalid input of a form after clicking a button (not submit). The form is rather large, and so the screen needs to scroll to the first invalid input.
这个AngularJS答案就是我所需要的,但不知道这样的指令是否会成为Angular 2中的方法?
This AngularJS answer would be what I would need, but didn't know if a directive like this would be the way to go in Angular 2:
Angular 2的实现方式是什么?感谢您的所有帮助!
What would be the Angular 2 way to do this? Thanks for all the help!
推荐答案
这对我有用.这不是最优雅的解决方案,但是鉴于Angular的局限性,我们所有人都在经历这一特殊任务,它做的工作.
This works for me. Not the most elegant solution, but given the constraints in Angular we are all experiencing for this particular task, it does the job.
scrollTo(el: Element): void {
if(el) {
el.scrollIntoView({ behavior: 'smooth' });
}
}
scrollToError(): void {
const firstElementWithError = document.querySelector('.ng-invalid');
this.scrollTo(firstElementWithError);
}
async scrollIfFormHasErrors(form: FormGroup): Promise <any> {
await form.invalid;
this.scrollToError();
}
这有效,使您可以逃避对DOM的操纵.它只是通过document.querySelector()
转到页面上带有.ng-invalid
的第一个元素,该元素将返回返回列表中的第一个元素.
This works, allowing you to evade manipulating the DOM. It simply goes to the first element with .ng-invalid
on the page through the document.querySelector()
which returns the first element in the returned list.
要使用它:
this.scrollIfFormHasErrors(this.form).then(() => {
// Run any additional functionality if you need to.
});
我也在Angular的Github页面上发布了此内容: https://github.com com/angular/angular/issues/13158#issuecomment-432275834
I also posted this on Angular's Github page: https://github.com/angular/angular/issues/13158#issuecomment-432275834
这篇关于Angular 2专注于Click/Event之后的第一个无效输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!