Angular 2表单验证器与“取消"按钮混淆 [英] Angular 2 form validators messing with the cancel button
问题描述
我有一个数据收集组件,其中包括取消"按钮,以取消整个过程.问题是,如果某些由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?
推荐答案
将事件从(单击)更改为(鼠标按下).在发生模糊事件之前调用mousedown.
Change the event from (click) to (mousedown). Mousedown is invoked before blur event.
所以不是这个<button (click)="cancel()">Cancel</button>
尝试:<button (mousedown)="cancel()">Cancel</button>
这篇关于Angular 2表单验证器与“取消"按钮混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!