1

我是 Angular 的新手,并且在观看教程时正在搞乱反应形式。我的 ngSubmit() 函数没有执行,当我单击提交按钮时没有任何反应,花一个小时试图找到根本原因。有人可以帮忙吗?

员工.ts

export class Employee {

  private name: string;
  private email: string;
  private salary: number;
  private notes?: string;

}

App.component.html

  <div class="container-fluid">
  <app-header></app-header>
</div>

<div class="row justify-content-lg-center">
  <div class="col-md-4">
    <app-employee-list></app-employee-list>
  </div>

  <div class="col-md-4">
    <app-employee-form></app-employee-form>
  </div>
</div>

员工组件.html

<form [formGroup]="reactiveForm" (submit)="employeeSubmit(this.reactiveForm.value)">
  <div class="input-group mb-3">
    <div class="input-group-prepend">
      <span class="input-group-text" id="basic-addon1">@</span>
    </div>
    <input formControlName="name" type="text" class="form-control" placeholder="Username" aria-label="Username"
           aria-describedby="basic-addon1">
  </div>

  <div class="input-group mb-3">
    <input formControlName="email" type="text" class="form-control" placeholder="Recipient's username" aria-label="Recipient's username"
           aria-describedby="basic-addon2">
    <div class="input-group-append">
      <span class="input-group-text" id="basic-addon2">@example.com</span>
    </div>
  </div>


  <div class="input-group mb-3">
    <div class="input-group-prepend">
      <span class="input-group-text">$</span>
    </div>
    <input formControlName="salary" type="text" class="form-control" aria-label="Amount (to the nearest dollar)">
    <div class="input-group-append">
      <span class="input-group-text">.00</span>
    </div>
  </div>

  <div class="input-group">
    <div class="input-group-prepend">
      <span class="input-group-text">With textarea</span>
    </div>
    <textarea formControlName="notes" class="form-control" aria-label="With textarea"></textarea>
  </div>

  <div class="input-group">
  <button type="button" class="btn btn-primary">Submit</button>
  </div>

</form>

员工表单组件.ts

import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';

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

  reactiveForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.reactiveForm = this.formBuilder.group({
      'name': [''],
      'email': [''],
      'salary': [''],
      'notes': ['']
    });
  }

  ngOnInit() {
  }

  employeeSubmit(value) {
    // tslint:disable-next-line:no-debugger
    debugger;
    console.log(this.reactiveForm.value);
  }

}
4

1 回答 1

1

你的按钮应该是 type submit,而不是 typebutton

<button type="submit">Submit</button>

将类型设置为button是按钮不应提交表单的特定指令。当表单中有其他不是主要提交按钮的按钮时,这很有用。

于 2020-02-14T14:04:22.880 回答