我有一个基本的Angular表单,其中包含prod_name
,prod_desc
,prod_price
,这些表单我当然想在提交表单时发送到服务器。
但是我想发送更多的数据和平信息,并且我不想为此设置隐藏的输入字段。
因此表单的剥离版本如下所示:
<form [formGroup]="productForm" (ngSubmit)="onFormSubmit(productForm.value)">
<mat-form-field class="example-full-width">
<input matInput placeholder="Product Name" formControlName="prod_name"
[errorStateMatcher]="matcher">
</mat-form-field>
<!-- Additional two form fields omitted for clarity -->
<div class="button-row">
<button type="submit" [disabled]="!productForm.valid" mat-flat-button color="primary"><mat-icon>save</mat-icon></button>
</div>
</form>
基本上,它调用onFormSubmit()
并将其传递给productForm.value
。
这是控制器的外观,为清楚起见,只剥离了必要的数据:
@Component({
//...
})
export class ProductAddComponent implements OnInit {
productForm: FormGroup;
updated_at: Date = null;
constructor(private router: Router, private api: ApiService, private formBuilder: FormBuilder) { }
ngOnInit() {
this.productForm = this.formBuilder.group({
'prod_name' : [null, Validators.required],
'prod_desc' : [null, Validators.required],
'prod_price' : [null, Validators.required]
});
}
onFormSubmit(form: NgForm) {
// Here I want to add current date as well to the form data before sending it
this.api.addProduct(form)
.subscribe(res => {
let id = res.id;
this.router.navigate(['/product-details', id]);
}, err => {
console.log(err);
});
}
}
在onFormSubmit()
函数中,我也想将当前日期传递给服务器。
不能选择表单模板中的隐藏字段。
我想在调用服务之前在onFormSubmit()
函数中执行此操作,但是我被卡住了。
对于基本设置附加数据以及表单数据(例如日期)并将其发送到服务器的方式,我将提供帮助。
答案 0 :(得分:3)
您可以复制表单数据,然后向其中添加任何内容。
onFormSubmit(form: NgForm) {
const dataForSubmit = {...form.value}; // copies the form data into a new variable
dataForSubmit.otherProperty = 'what ever you want'; // add whatever data is needed
this.api.addProduct(dataForSubmit)
.subscribe(res => {
let id = res.id;
this.router.navigate(['/product-details', id]);
}, err => {
console.log(err);
});
}
在我的应用程序中,我经常为所有数据定义一个接口。我将数据输入该界面,仅将所需的字段复制到表单。然后保存,将更改从表单复制到原始对象上。
界面
export interface Product {
id: number;
productName: string;
productCode: string;
}
当然,系统ID不会出现在UI中。
组件代码
// Update the data on the form
// after a get
this.productForm.patchValue({
productName: this.product.productName,
productCode: this.product.productCode
});
// The save
saveProduct(): void {
if (this.productForm.valid) {
// Copies any changed form values over the original product values
const p = { ...this.product, ...this.productForm.value };
// Call the http service put to save the data `p`
}
}