我有一个数据收集组件,其中包含取消按钮以取消整个过程.问题是,如果某些由Angular 2验证器验证的
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:
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 }
我不知道为什么会这样.有任何想法吗?
解决方法
将事件从(单击)更改为(mousedown).在模糊事件之前调用Mousedown.
因此,而不是这个< button(click)=“cancel()”>取消< / button>
试试这个:< button(mousedown)=“cancel()”>取消< / button>