4

I have components called demo, demo component have 3 input fields and an button.Like this:

enter image description here

After clicking button(i,e submit) i am navigating to another component called home.This scenario is working fine for me, But i have added some validation for first/last-name and email.

If the user enters all the required input fields then only it as to navigate to another component (i,e home).But it is navigating without entering/validating the required input fields.

While surfing i got some examples:

1) Example 1
2) Example 2

But these are for template-driven forms. I am using reactive forms.

Here is the Stakcblitz DEMO.

Empty_Soul
  • 799
  • 2
  • 13
  • 31

3 Answers3

2

make the button disabled since the form is valid

<button mat-raised-button  type="submit" color="primary" [disabled]="!addForm.valid"  (click)="onaddCustomer()">Submit</button>

and navigate in the click function

onaddCustomer(){

this.router.navigate(['/home']);

}

with out using [disabled]

check whether form valid or not in your click function

<button mat-raised-button  type="submit" color="primary"   (click)="onaddCustomer()">Submit</button>

and in click function

onaddCustomer(){

if(this.addForm.valid){
this.router.navigate(['/home']);
    }
 }
Arun Kumaresh
  • 6,211
  • 6
  • 32
  • 50
2

Simply disable the submit button till the form is valid, no other change is required.

Like that [disabled]="!addForm.valid"i.e. in your case:-

<button mat-raised-button [routerLink]="['../home']" type="submit" color="primary" [disabled]="!addForm.valid" (click)="onaddCustomer()">Submit</button>

OR

If you don't want to disable the button then remove [routerLink]="['../home']" from the button and in the component method add a condition for validation like:-

onaddCustomer(){

if (this.addForm.invalid) { return; }

this.router.navigate(['/home']);

}

Gourishankar
  • 906
  • 1
  • 7
  • 14
1

Disabling just submit button may cause problems if you hit enter in an input as it submits the form. If you structured your form properly (as a reactive form), you could use a function on form submit.

<form [formGroup]="yourReactiveFormGroup" (ngSubmit)="onSubmit()">
  ...
</form>

and in onSubmit() function:

onSubmit() {

    // Stop if invalid
    if (this.yourReactiveFormGroup.invalid) {
        return;
    }

    this.router.navigate(['/your-route']);
}
Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35