1

In a Form I have a button that when clicked, it should submit the form and at the same time redirect to another component with the routerLink.

Here is what i have:

    <div class="container-fluid padding_elementos">
    <div class="row">
        <div class="card align-self-center">
            <div class="card-body">
                <form [formGroup]="forma" (ngSubmit)="saveChanges()">
                              <div class="form-group">
                                <label for="exampleInputEmail1">Correo Electrónico:</label>
                                <input type="email" class="form-control" placeholder="E-mail"
                                type="text"
                                formControlName="Correo">

                              </div>
                              <hr>
                              <div class="form-group">
                                <input type="password" class="form-control"  placeholder="Nueva Contraseña" formControlName="Password">
                                <br>
                                <input type="password" class="form-control"  placeholder="Repite Contraseña"
                                name="samePassword" formControlName="SamePassword">

                              </div>

                              <button type="submit" class="btn btn-primary btn-block" [routerLink]="['/login']">Guardar</button>
                </form>
                <br>
                {{forma.valid}}
            </div>
        </div>
    </div>
</div>

And in my TS file:

    this.forma = new FormGroup({
  'Correo': new FormControl('', Validators.required),
  'Password': new FormControl('', Validators.required),
  'SamePassword': new FormControl()
})
  guardarCambios(){
console.log(this.forma.value)
this.forma.reset();}

The submission works well, but when I add the routerLink I get this message:

Form submission canceled because the form is not connected

and it does not submit anything. What am I doing wrong?

rmcsharry
  • 5,363
  • 6
  • 65
  • 108
CJP
  • 89
  • 2
  • 13
  • 4
    Why don't you do the redirection in the `saveChanges()` method ... afer the form is submmited? – Yordan Nikolov Apr 12 '18 at 10:08
  • You should not be trying to submit AND redirect at the same time - the submit needs time to send the data to the server. What happens if there is an error? You need to STOP the redirect and show the errors. Therefore you should ONLY navigate AFTER the changes have saved successfully. Hence call navigate in the saveChanges method, do not use routerLink in the template. – rmcsharry Apr 12 '18 at 10:17

1 Answers1

3

You've bound to the submit event of your form

(ngSubmit)="saveChanges()"

Since you do that, you should not redirect from your button, but from your component.

Add a dependency to the router

constructor(private router: Router) {}

And in your function

saveChanges() {
  // ... Do what you have to do then
  this.router.navigate(['/login']);
}