角度:为什么单击保存按钮时会自动导航

时间:2019-05-08 11:40:24

标签: angular forms navigation

当我单击项目的“保存”按钮时,我不确定为什么导航器会返回原来的状态。 此按钮应仅更改Boolean和console.log“保存!”但仍保留在当前视图中,由于某种原因,它可以返回到某个级别...

这里是StackBlitz https://stackblitz.com/github/ardzii/test

这是我的模板(/ 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>

这是随附的TS文件(/ 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!');
  }
}

我希望足够了...

2 个答案:

答案 0 :(得分:2)

type以外,每个没有明显服装submit的按钮都会默认type="submit"。对于您的代码,保存按钮将调用onSubmit()

Avoid Angular2 to systematically submit form on button click

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

  

“未指定type属性的按钮元素表示相同   事物作为按钮元素,其类型属性设置为“提交”。”

答案 1 :(得分:1)

您的按钮正在调用onSubmmit函数,在此函数中,您具有以下代码:

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

因此它将您重定向到此路由。

您可以在按钮上添加type =“ button”,然后,它将对onSaveInfo函数进行校准。