我陷入了组件和模板之间的表单绑定中。我想为发布方法实现REST API
component.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>
Component.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函数中传递表单值。这样我就可以在服务器端访问它。
答案 0 :(得分:0)
您的方法addEmployee
不需要任何参数,因为您使用的是模板驱动的方法来绑定表单数据,同时您也没有从html传递任何数据。将您的方法签名更改为addEmployee() { //logic }
。单击按钮后,它将触发此方法,并让您将当前值绑定到对象
答案 1 :(得分:0)
使用console.log检查表单值, 似乎表单值已正确绑定。 在传递到http post之前尝试对对象进行字符串化
JSON.stringify(this.employeeDetails)