Angular 2 表单验证器弄乱了取消按钮 [英] Angular 2 form validators messing with the cancel button

查看:28
本文介绍了Angular 2 表单验证器弄乱了取消按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据收集组件,其中包括用于取消整个过程的取消"按钮.问题是,如果由 Angular 2 验证器验证的某些 HTML 输入字段具有焦点且无效,并且我按下取消按钮,则不会删除该组件.相反,验证器将触发,取消按钮按下将被忽略.在验证器抱怨之后,我必须第二次按下它才能使组件消失.取消按钮本身只会触发远离组件的路由.相关代码:

I have a data gathering component which includes 'cancel' button to cancel the whole process. The problem is, if some of the HTML input fields which are validated by Angular 2 validators have focus, and are not valid, and I press the cancel button, the component is not removed. Instead, validators will fire and the cancel button press will be ignored. I have to press it for the second time, after the validators complain, to make the component disappear.Cancel button itself simply triggers routing away from the component. Relevant code:

component.html

component.html

<form [formGroup]="addReminderForm" (ngSubmit)="onSubmit(addReminderForm.value)">
  <input type="text" [formControl]="addReminderForm.controls['text']" />
  <div class="error" *ngIf="addReminderForm.controls['text'].hasError('required') &&
  addReminderForm.controls['text'].touched">You must enter reminder text</div>

  <button type="submit" [disabled]="!addReminderForm.valid" >Add Reminder</button>
</form>
<button (click)="cancel()">Cancel</button>

component.ts:

component.ts:

ngOnInit() {
  this.addReminderForm = this.fb.group({  
      'text': ['', Validators.compose([Validators.required, Validators.maxLength(20)])]
  });
}
cancel() {
    // Simply navigate back to reminders view
    this.router.navigate(['../'], { relativeTo: this.route }); // Go up to parent route     
 }

我不知道为什么会发生这种情况.有什么想法吗?

I have no idea why this happens. Any ideas?

推荐答案

将事件从 (click) 更改为 (mousedown).Mousedown 在模糊事件之前调用.

Change the event from (click) to (mousedown). Mousedown is invoked before blur event.

所以代替这个

So instead of this <button (click)="cancel()">Cancel</button>

试试这个:

try this: <button (mousedown)="cancel()">Cancel</button>

这篇关于Angular 2 表单验证器弄乱了取消按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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