Angular 2 关注点击/事件后的第一个无效输入 [英] Angular 2 Focus on first invalid input after Click/Event

查看:21
本文介绍了Angular 2 关注点击/事件后的第一个无效输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的要求,希望得到一些帮助.

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:

在 AngularJs 表单中设置第一个无效输入的焦点

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/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 关注点击/事件后的第一个无效输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆