Angular2:Ajax 表单数据返回空值
Angular2 : Ajax form data return null
我正在尝试在Angular2中设置动态形式。因此,在我的ngOnInit函数中,我发出了一个Ajax请求来获取带有表单数据的JSON。喜欢这个:
export class CustomerEditComponent{
private customer : Customer = new Customer();
private customerForm;
constructor(private _CustomersService: CustomersService, private _routeParams: RouteParams, private _fb: FormBuilder){
this.customerForm = _fb.group({
name: [],
job: [],
arrival_date: []
});
}
ngOnInit(){
let id = this._routeParams.get('id');
this._CustomersService.getById(id).subscribe(res => {
this.customer = res;
});
}
onSubmit(event){
console.log(event);
}
}
因此,在组件构造中,"客户"等于最新的客户。(所有属性均为空)。但就在之后,我们为每个属性设置了值。
没问题,我的输入具有正确的值。
但是,如果我提交表单,则表单值等于:
Object {name: null, job: null, arrival_date: null}
(但视图中的窗体已正确填充)。
这是我的表格(浓缩):
<form [ngFormModel]="customerForm" (ngSubmit)="onSubmit(customerForm.value)">
<input md-input [(value)]="customer.name">
<input md-input [(value)]="customer.job">
<input md-input type="date" [(value)]="customer.arrival_date">
<button type="submit">Save</button>
</form>
我使用 [(值)] 导致 ng2 材料包。(我已经尝试使用ngControl)。
我认为我的代码对此功能是"错误的",但我不知道在哪里。
谢谢!
编辑:
我找到了答案!使用 ng2-material,我们需要在每个输入上一起设置 [(值)] 和 [(ngModel)],如下所示:
<form [ngFormModel]="customerForm" (ngSubmit)="onSubmit(customerForm)">
<input md-input [(value)]="customer.name" [(ngModel)]="customer.name">
<input md-input [(value)]="customer.job" [(ngModel)]="customer.job">
<input md-input type="date" [(value)]="customer.arrival_date" [(ngModel)]="customer.arrival_date">
<button type="submit">Save</button>
</form>
[(值)] 由 ng2-material 用于设置值"在前面"。
我认为
问题是您没有将表单输入与模板中 ngFormControl
指令中的控制器相关联。您应该以这种方式重构:
<form [ngFormModel]="customerForm" (ngSubmit)="onSubmit(customerForm.value)">
<input md-input [(value)]="customer.name"
ngFormControl="name">
<input md-input [(value)]="customer.job"
ngFormControl="job">
<input md-input type="date" [(value)]="customer.arrival_date"
ngFormControl="arrival_date">
<button type="submit">Save</button>
</form>
请参阅ng2材料示例的链接:https://github.com/justindujardin/ng2-material/blob/master/examples/components/input/form_builder.html
否则,为什么不使用customer
对象而不是customerForm.value
对象?
希望对您有所帮助,蒂埃里
相关文章:
- Model中的Typeahead返回空值以形成输入字段
- 为什么数据列表选项的id返回空值
- 从角度服务返回空值的变量
- 为什么 document.getElementById('files') 返回空值
- AJAX 成功:函数(响应)返回空值
- Cookie 在 IE 中始终返回空值
- 如果在过滤器中返回空值,如何显示“未找到书籍”行
- 获取返回空值的元素 { 绝对|相对|固定 }
- j查询选择选项值返回空值
- D3 albersUsa 投影函数返回空值
- Angular2:Ajax 表单数据返回空值
- 本地存储在火狐中无法按预期工作.返回空值的对象
- 访问 iFrame 中的元素返回空值
- Json 数组返回空值
- 中继:获取递归数据返回空值
- 文件上传 - 返回空值
- 为什么"document.styleSheets”;每次刷新3到5次浏览器后返回空值
- 为什么动态文本框返回空值
- JQuery Mobile Slider在事件之后返回空值
- 为什么document.getElementById返回空值