8

I have a reactive form which has Cancel and Submit buttons:

<button (click)="cancel($event)" type="button" class="ui button">Cancel</button>
<button [disabled]="..." type="submit" class="ui button primary">Store</button>

and now if I click on a Submit (Store) button validation kicks in - all good. But if I click on Cancel it also trigger validation. I wonder why? I don't need any validation on Cancel. What do I need to do to turn it off?

Harry Ninh
  • 16,288
  • 5
  • 60
  • 54
AlexB
  • 4,167
  • 4
  • 45
  • 117

3 Answers3

1

You can simply 'reset' the formControls in the parent formGroupon cancel button click if that is okay for you.

cancel() {
 this.form.reset();
}
amal
  • 3,140
  • 1
  • 13
  • 20
1

It works with event.preventDefault()

<button (click)="cancel($event)">Cancel</button>
cancel(event) {
    event.preventDefault()
}
Boris
  • 441
  • 4
  • 10
  • 1
    I prefer this solution much more than the others. This also really helps if you're looking for buttons like, "+" or "-" (to remove elements from a list) from triggering form validation. And it doesn't seem to have any undesirable side effects! – Nick Betcher Oct 13 '20 at 23:41
0

I would re-initialize the FormGroup when the Cancel button is clicked. This would completely wipe the form and force all of the input states to be prestine again. You should be using input states to verify whether they have been used or not if you aren't already. It will prevent validation from running on a form input that hasn't been used yet.

Component

constructor() {
    this.Form = initForm();
}

initForm() {
    return this._FormBuilder.group({
        fieldOne: ['', Validators.required]
    })
}

Input

 <div class="ui input" [class.error]="Form.get('fieldOne').dirty && !Form.get('fieldOne').valid">
  <input type="text" placeholder="Search..." formControlName="fieldOne">
</div>

Button

<button (click)="initForm()" type="button" class="ui button">Cancel</button>

P.S. it looks like you are using Semantic UI, so my HTML is formatted accordingly. If not you'll need to rework it a little.

joshrathke
  • 7,564
  • 7
  • 23
  • 38