CJP
CJP

Reputation: 99

Submission Canceled with Angular Forms

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?

Upvotes: 1

Views: 337

Answers (1)

user4676340
user4676340

Reputation:

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

Upvotes: 3

Related Questions