【发布时间】:2016-02-03 09:18:18
【问题描述】:
我正在尝试在 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>
我使用 [(value)] 导致 ng2-material 包。 (我已经尝试过使用 ngControl)。
我认为我的代码关于此功能的“错误”,但我不知道在哪里。
谢谢!
编辑:
我找到了答案! 使用 ng2-material,我们需要在每个输入上同时设置 [(value)] 和 [(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>
[(value)] 被 ng2-material 用来设置值'on front'。
【问题讨论】:
-
你的类声明中不是缺少
implements OnInit吗?export class CustomerEditComponent implements OnInit? -
在我当前的版本(2.0.0-beta.2)中,我们不需要实现 OnInit(它可以不使用)。
-
哦,好吧,在
beta.2中不知道这一点:)
标签: javascript forms angular formbuilder