ngSubmit不触发该功能

时间:2017-06-01 06:32:19

标签: angular

<div [hidden]="submitted">
<div class="container" >
    <h1>Employee Form</h1>
    <form  (ngSubmit)="onSubmit()" #employeeform= "ngForm" >
      <div class="form-group ">
        <label for="firstname" class="col-md-3">FirstName:</label>
        <input type="text" class="form-control" id="firstname" required [(ngModel)]="model.firstname" name="firstname" #firstname="ngModel">

        <div [hidden]= "firstname.valid || firstname.pristine" 
                class="alert alert-danger" >
            FirstName Required
        </div>
      </div>
      <div class="form-group ">
        <label for="lastname">LastName:</label>
        <input type="text" class="form-control" id="lastname" required [(ngModel)]="model.lastname" name="lastname" #lastname="ngModel">
        <div [hidden]="lastname.valid || lastname.pristine "
                class="alert alert-danger" >
            LastName Required
        </div>

      </div>
      <div class="form-group " >
        <label for="employeetype">Employee Type:</label>
        <select class="form-control" id="employeetype" [(ngModel)]="model.employeetype" name="employeetype"> 
            <option *ngFor="let emtype of employeetype"[value]="emtype" >{{emtype}}</option>
        </select>
      </div>
      <input type="submit" class="btn btn-success" (click)="newEmployee() ;employeeform.reset()" [disabled]="!employeeform.form.valid" value="submit">

    </form>
</div>
</div>
<div [hidden]="!submitted">
  <h2>You submitted the following:</h2>
  <div class="row">
    <div class="col-xs-3">Name</div>
    <div class="col-xs-9  pull-left">{{ model.firstname }}</div>
  </div>
  <div class="row">
    <div class="col-xs-3">Alter Ego</div>
    <div class="col-xs-9 pull-left">{{ model.lastname }}</div>
  </div>
  <div class="row">
    <div class="col-xs-3">Power</div>
    <div class="col-xs-9 pull-left">{{ model.employeetype }}</div>
  </div>
  <br>
  <button class="btn btn-primary" (click)="submitted=false">Edit</button>
</div>

我的HTML文件和我的Component.ts如下

import { Component } from '@angular/core';

import { Employee } from './employee';

@Component({
    selector: 'employee-form',
    templateUrl: './employee-fom.controller.html'
})

export class EmployeeFormComponent{

    employeetype=['Consultant','Fulltime Hourly','Fulltime Salaried','Parttime'];

    model = new Employee(18,'sandeep','chetikam',this.employeetype[1]);

    submitted = false;

    onSubmit() { this.submitted = true;console.log(this.submitted); }


    newEmployee() {
  this.model = new Employee(42, '', '');

}
}

因此在此ngSubmit show中触发onSubmit函数并将提交更改为true,以便激活[hidden] =“!submitted”。 但是ngSubmit没有触发onSubmit函数。

我无法理解为什么。

1 个答案:

答案 0 :(得分:1)

您在相同的按钮类型提交中调用newEmployee()employeeform.reset()个函数。请改变这个。我认为这将是问题所在。

请从按钮中删除该功能并将其包含在组件

 onSubmit() { 
    this.submitted = true;
    console.log(this.submitted);
    this.model = new Employee(42, '', '');
    this.employeeform.reset();
}