0

I'm not sure to get why is my navigator going back when I click on the "save" button of my project. This button should only change a Boolean and console.log "saving!" but remain on the current view and for some reason it goes back a level...

Here's on StackBlitz https://stackblitz.com/github/ardzii/test

Here's my template (/src/app/customers/customer-edit/):

<mat-spinner *ngIf="isLoading"></mat-spinner>

<form (ngSubmit)="onSubmit()" [formGroup]="customerForm" *ngIf="!isLoading">
  <div class="btn-row">
    <button
    mat-raised-button
    type="submit"
    color="accent">{{ editMode ? "Update Customer" : "Add Customer"}}</button>
    <button
    mat-raised-button
    routerLink="/customers"
    color="accent"
    [disabled]="savedInfo">
      Back
    </button>
  </div>

  <mat-card>
    <mat-tab-group>
        <mat-tab label="Info">
          <br>

          <mat-form-field>
              <input
              matInput
              type="text"
              placeholder="Legal name"
              name="name"
              formControlName="name">
              <mat-error *ngIf="customerForm.get('name').invalid">Please enter a valid name</mat-error>
          </mat-form-field>
          <mat-form-field>
            <input
            matInput
            type="text"
            placeholder="VAT number"
            name="vat"
            formControlName="vat">
            <mat-error *ngIf="customerForm.get('vat').invalid">Please enter a valid VAT number</mat-error>
          </mat-form-field>

          <p>
            <button
            mat-raised-button
            (click)="onSaveInfo()">
            Save Info
            </button>
          </p>

        </mat-tab>

        <mat-tab label="Documents">
          <mat-list>
              <mat-nav-list>
                <a mat-list-item (click)="fsPicker.click()">Upload financial statements</a><input type="file" #fsPicker>
                <a mat-list-item (click)="cdPicker.click()">Upload the constitutional documents</a><input type="file" #cdPicker>
                <a mat-list-item (click)="idPicker.click()">Upload the ID</a><input type="file" #idPicker>
                <a mat-list-item (click)="adPicker.click()">Upload the bank account details</a><input type="file" #adPicker>
              </mat-nav-list>
          </mat-list>
        </mat-tab>
      </mat-tab-group>

  </mat-card>
</form>

and here's the TS file that goes with it (/src/app/customers/customer-edit/):

import { Component, OnInit } from '@angular/core';
import { FormGroup, Validators, FormControl } from '@angular/forms';
import { ActivatedRoute, ParamMap, Router } from '@angular/router';

import { CustomerService } from '../customer.service';
import { Customer } from '../customer-model';

@Component({
  selector: 'app-customer-edit',
  templateUrl: './customer-edit.component.html',
  styleUrls: ['./customer-edit.component.css']
})
export class CustomerEditComponent implements OnInit {

  private id: string;

  savedInfo = false;
  isLoading = false;
  name: string;
  vat: string;
  editMode = false;
  customer: Customer;
  customerForm: FormGroup;

  constructor(
    private customerService: CustomerService,
    private route: ActivatedRoute,
    private router: Router) { }

  ngOnInit() {
    this.isLoading = true;
    this.customerForm = new FormGroup({
      name: new FormControl(null, {validators: Validators.required}),
      vat: new FormControl(null, {validators: Validators.required})
    });
    this.route.paramMap
      .subscribe(
        (paramMap: ParamMap) => {
          if (paramMap.has('id')) {
            this.editMode = true;
            this.id = paramMap.get('id');
            this.customerService.getCustomer(this.id)
              .subscribe(customerData => {
                this.customer = customerData as Customer;
                this.customerForm.setValue({
                  name: this.customer.name,
                  vat: this.customer.vat
                });
                this.isLoading = false;
              });
          } else {
            this.editMode = false;
            this.id = null;
            this.isLoading = false;
          }
      });
  }

  onSubmit() {
    if (!this.customerForm.valid) {
      return;
    }
    this.isLoading = true;
    if (!this.editMode) {
      const newCustomer: Customer = {
        id: null,
        name: this.customerForm.value.name,
        vat: this.customerForm.value.vat
      };
      this.customerService.addCustomer(newCustomer);
      this.customerForm.reset();
    } else {
      const updatedCustomer: Customer = {
        id: this.id,
        name: this.customerForm.value.name,
        vat: this.customerForm.value.vat
      };
      this.customerService.updateCustomer(this.id, updatedCustomer);
    }
    this.router.navigate(['/customers']);
  }

  onSaveInfo() {
    this.savedInfo = true;
    console.log('Saving info!');
  }
}

I hope it's enough...

Martin Carre
  • 1,157
  • 4
  • 20
  • 42
  • I imagine it is because you're using `ngSubmit` on the form, *and* you have `click` firing something on the save button. Use one, or the other. – R. Richards May 08 '19 at 11:46

2 Answers2

2

Every button without explicit attibute type other than submit will default to type="submit". Means for your code the save button will call onSubmit().

Avoid Angular2 to systematically submit form on button click

http://w3c.github.io/html-reference/button.html

"A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit"."

Severin Klug
  • 733
  • 5
  • 9
1

Your button is calling onSubmmit function, and in this function, you have this code :

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

so it's redirecting you to this route.

you can add type="button" to your button and after that, it will cal your onSaveInfo function.