If I submit a form using button type="submit"
the form validation messages appear and everything is fine. However if I have a button (or link) with (click)="myhandler()"
then the validations do not appear.
How can I either:
Note: These are simple validations like required on input fields.
Sample Code:
<form (ngSubmit)="save()">
<input required type='text' [(ngModel)]="name">
<!-- Shows validation messages but still calls save() -->
<button (click)="save()">Click</button>
<!-- Only submits if valid and shows messages -->
<button type="submit">Submit</button>
</form>
<!-- does not even show validation messages, just calls save -->
<button (click)="save()">Click 2</button>
Please note: this approach is for reactive forms.
I used markAsTouched()
property to run validations on a button click.
Suppose the following button is outside the form:
<button type="button" (click)="validateForm()">Submit</button>
Now, in the validateForm
method if the form is invalid, you can set markAsTouched()
property for each of the form controls and angular will show validation messages.
validateForm() {
if (this.myformGroup.invalid) {
this.myformGroup.get('firstName').markAsTouched();
this.myformGroup.get('surname').markAsTouched();
return;
}
// do something else
}
provided you have validation messages setup in your html like
<mat-error *ngIf="myformGroup.get('firstName').hasError('required')">
first name is required
</mat-error>
and you have required field validation setup in your form group builder like
firstName: ['', Validators.required]
Button with type submit triggers form submit automatically, i guess you have to trigger form submit manually:
<form (ngSubmit)="save()" #form="ngForm">
<button (click)="form.onSubmit()">Click 2</button>
Why "ngForm"? A directive's exportAs property tells Angular how to link local variable to the directive. We set name to ngForm because the NgControlName directive's exportAs property happens to be "ngForm".
documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With