【问题标题】:Angular: Why does it navigates automatically when clicking the save buttonAngular:为什么单击保存按钮时会自动导航
【发布时间】:2019-09-26 03:25:11
【问题描述】:

当我单击项目的“保存”按钮时,我不确定为什么我的导航器会返回。 此按钮应仅更改布尔值和 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!');
  }
}

我希望这就够了……

【问题讨论】:

  • 我想这是因为你在表单上使用了ngSubmit并且你有click 在保存按钮上触发了一些东西。使用一个或另一个。

标签: angular forms navigation


【解决方案1】:

除了submit 之外,没有明确属性type 的每个按钮将默认type="submit"。意味着您的代码保存按钮将调用onSubmit()

Avoid Angular2 to systematically submit form on button click

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

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

【讨论】:

    【解决方案2】:

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

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

    所以它会将你重定向到这条路线。

    您可以将 type="button" 添加到您的按钮,然后它会调用您的 onSaveInfo 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      相关资源
      最近更新 更多