Search code examples
angularangular2-formscancellation

Angular 2 form validators messing with the cancel button


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

<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     
 }

I have no idea why this happens. Any ideas?


Solution

  • 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>