您需要创建一个函数来将 NgbDateStructure 转换为您在 dbs 中使用的数据类型
通常您向数据库发送 ISO 格式 yyyy-MM-dd 的字符串
ngbDateToString(date:any)
{
return date.year+'-'+('0'+date.month).slice(-2)+('0'+date.day).slice(-2)
}
或者是使用日期对象
ngbDateToDate(date:any)
{
return new Date(date.year+'-'+('0'+date.month).slice(-2)+('0'+date.day).slice(-2))
}
但我看到一些混淆了您的代码。我想您使用服务获取数据。我喜欢从 http.client 获取数据时,在 Date 对象中转换 de props 类型 Date - 通常您将类型 date 作为字符串接收,因此,在服务中使用 map 来转换数据
//declare a interfacte in the service
export DataInterface
{
DueDate:Date|string
ExpiryDate:Date|string
... rest of properties..
}
getData(id):Observable<DataInterface>
{
//generally, you received DueDate or ExpiryDate as string, so we not use only
//return this.httpClient.get('....') as DataInterface;
//else transform the string to Date
return this.httpClient.get('....').pipe(
map(res=>{
res.DueDate=new Date(res.DueDate)
res.ExpiryDate=new Date(res.ExpiryDate)
return res;
}
))
}
如果您有获取对象列表的函数,则同理
getList(id):Observable<DataInterface[]>
{
return this.httpClient.get('....').pipe(
map(res=>{
res.forEach(x=>{
x.DueDate=new Date(x.DueDate)
x.ExpiryDate=new Date(x.ExpiryDate)
}
return res;
}
))
}
但是 ngb-datepicker 使用 NgbDateStructur,所以你需要在接收数据和发送数据时进行转换。通常你在组件中有一个函数 createForm
createForm(data:DataInterface=null)
{
data=data || {} as DataInterface
return new FormGroup({
DueDate:new FormControl(data.DueDate?
{
year:data.DueDate.getFullYear(),
month:data.DueDate.getMonth()+1,
day:data.DueDate.getDate()
}:
null),
ExpiryDate:new FormControl(data.ExpiryDate?
{
year:data.ExpiryDate.getFullYear(),
month:data.ExpiryDate.getMonth()+1,
day:data.ExpiryDate.getDate()
}:
null),
..rest of FormControl, e.g...
id:new FormControl(data.id);
})
}
现在你有一个表格。看到只使用formControlName
<form [formGroup]="form" (submit)="submit(form)">
<div>
<input class="form-control" placeholder="yyyy-mm-dd"
name="dp" formControlName="DueDate" ngbDatepicker
class="rtl" [firstDayOfWeek]="7"
#dDueDate="ngbDatepicker">
<button class="btn btn-outline-secondary calendar" (click)="dDueDate.toggle()"
type="button"></button>
</div>
<div>
<input class="form-control" placeholder="yyyy-mm-dd"
name="do" formControlName="ExpiryDate" ngbDatepicker
class="rtl" [firstDayOfWeek]="7"
#dExpiryDate="ngbDatepicker">
<button class="btn btn-outline-secondary calendar" (click)="ExpiryDate.toggle()"
type="button"></button>
</div>
..rest of FormControls in the way, e.g...
<input formControlName="id">
.....
<button type="submit">submit</submit>
</form>
在您的 component.ts 中
//in ngOnInit()
ngOnInit()
{
..get the id from params or whatever
this.dataService.getData(id).subscribe(res=>{
this.form=this.createForm(res);
})
}
在提交中我们可以先使用相关的功能
submit(form:FormGroup)
{
if (form.valid)
{
const data={...form.value} //make a copy
data.DueDate=this.ngbDateToString(data.DueDate)
data.ExpiryDate=this.ngbDateToString(data.ExpiryDate)
this.dataService.updateData(data).subscribe(res=>{
console.log(res)
})
}
}