Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Form Invalid Does Not Prevent Enter From Submitting The Form

I have a simple form with several fields, a Cancel button and a Submit button. I am using Angular Material within the form for the controls. I have developed a custom validation directive which makes the form invalid if certain conditions are met. The validation makes the Submit button disable, as expected, but the Enter button on the keyboard is not disabled when the form is invalid.

I don't want the Enter button always disabled, only when the form is invalid. Can this be achieved?

My form is declared as follows:

<form class="dialog-form"
          novalidate
          #areaForm="ngForm"
          (ngSubmit)="onSubmit()">

My buttons are as follows:

<mat-dialog-actions align="end">
    <button mat-button
            [mat-dialog-close]="true"
            (click)="onCancel()">
        Cancel
    </button>

    <button mat-button
            [mat-dialog-close]="true"
            color="primary"
            type="button"
            (click)="onSubmit()"
            [disabled]="areaForm.form.invalid">
        {{data.buttonText}}
    </button>
</mat-dialog-actions>

Any guidance would be welcome. Thanks.

Edit Creating an @Input reference to the FormGroup appears to allow me to check if the form is valid before closing the mat-dialog and submitting the form:

onSubmit() {
    if (this.form.valid) {

        // Close the dialog.
        this.dialogRef.close(this.areaForCreation);
    };
};
like image 995
TDC Avatar asked Dec 10 '25 11:12

TDC


1 Answers

It should be areaForm.invalid not areaForm.form.invalid

like image 146
Vivek Doshi Avatar answered Dec 12 '25 08:12

Vivek Doshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!