angular 7 ngmodel组件和表单绑定。

问题描述 投票:0回答:2

我卡在了组件和模板之间的表单绑定上,我想为post方法实现REST API。我想为post方法实现REST API。

组件.html

  <div class="container custom-container">
    <div class="col-md-12">
      <h3 class="mb-3 text-center">Create Employee</h3>

<div class="form-group">
  <input type="text" [(ngModel)]="employeeDetails.name" class="form-control" placeholder="Name">
</div>

<div class="form-group">
  <input type="text" [(ngModel)]="employeeDetails.email" class="form-control" placeholder="Email">
</div>


<div class="form-group">
  <input type="text" [(ngModel)]="employeeDetails.phone" class="form-control" placeholder="Phone">
</div>

<div class="form-group">
  <button class="btn btn-success btn-lg btn-block" (click)="addEmployee()">Create Employee</button>
</div>

组件.ts

   import { Component, OnInit, Input } from '@angular/core';
   import { Router } from '@angular/router';
   import { RestApiService } from "../shared/rest-api.service";
   @Component({
      selector: 'app-employee-create',
      templateUrl: './employee-create.component.html',
      styleUrls: ['./employee-create.component.css']
   })
  export class EmployeeCreateComponent implements OnInit {

  @Input() employeeDetails = { name: '', email: '', phone: 0 }

  constructor(
     public restApi: RestApiService, 
     public router: Router
  ) { }

  ngOnInit() { }

  addEmployee(dataEmployee) {
      this.restApi.createEmployee(this.employeeDetails).subscribe((data: {}) => {
      this.router.navigate(['/employees-list'])
     })
    }
  }

我想在函数createEmployee中传递表单值。这样我就可以在服务器端访问这个值。

angular angular7 angular-ngmodel
2个回答
0
投票

您的方法 addEmployee 不需要任何参数,因为你使用模板驱动的方法来绑定你的表单数据,同时你也没有从html中传递任何数据。addEmployee() { //logic }. 一旦你点击按钮,它将触发这个方法,并得到你的当前值绑定到对象。


0
投票

用 console.log 检查表单值,似乎表单值被正确绑定。试试在传递给http post之前对对象进行字符串化。

JSON.stringify(this.employeeDetails)
© www.soinside.com 2019 - 2024. All rights reserved.