Search code examples
angularangular-materialangular6angular-forms

Navigate to particular component only after filling required input fields


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.


Solution

  • 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']);
        }
     }