之前我使用过模板驱动的表单,我对于反应式表单如何将数据存储到我的数据库感到有些困惑。最初我只想使用 [(ngModel)] =" user.date" 。如何在提交时存储数据?我按如下方式构建了一个:
this.formGroup = this._formBuilder.group({
formArray: this._formBuilder.array([
this._formBuilder.group({
dateFormCtrl: ['', Validators.required]
}),
this._formBuilder.group({
emailFormCtrl: ['', Validators.email]
}),
])
});
这是我想要存储到db的输入示例:
<input formControlName="dateFormCtrl" matInput [matDatepicker]="picker" [max]="maxDate" [min]="minDate" placeholder="When is your event?"(click)="picker.open()" readonly>
ATM我有这个功能,我为模板驱动的表单构建了存储数据:
create() {
this.http.post('http://localhost:3000/user', this.user).subscribe(res => { ............
答案 0 :(得分:1)
你的表格应该像
this.form = this._formBuilder.group({
dateFormCtrl: ['', Validators.required],
emailFormCtrl: ['', Validators.email]
});
您的提交方法应该像
onSubmit(): void{
const formObj ={
date: this.form.value.dateFormCtrl,
email: this.form.value.emailFormCtrl,
}
this.http.post('http://localhost:3000/user', formObj).subscribe(res =>
}
答案 1 :(得分:0)
如果要将表单数据动态保存到服务器,则可以遵循以下代码。这是最好的选择。
在您的component.ts文件中:
form: FormGroup;
payLoad = '';
onSubmit() {
this.payLoad = JSON.stringify(this.form.value);
this.serverService.storeServers(this.payLoad)
.subscribe(
(response) => console.log(response),
(error) => console.log(error)
);
}
在您的service.ts文件中:
constructor(private http: HttpClient) { }
storeServers(payLoad: any) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.post(' ***Complete URL*** ', payLoad, httpOptions);
}