问题描述
我有来自 ngb-datepicker here 的范围选择弹出窗口。 我从后端获得了初始日期,它工作正常。但是当我更新日期时,它在输入字段中没有改变。如何修复此错误?
<div class="form-group">
<div class="input-group">
<input
#dpFromDate
class="form-control"
placeholder="From (YYYY-MM-DD)"
name="dpFromDate"
[(ngModel)]="splitRuleDetail.startDate"
[ngModelOptions]="{updateOn: 'blur'}"
(input)="fromDate = validateInput(fromDate,dpFromDate.value)"
/>
<div class="input-group-append">
<button
class="btn btn-outline-secondary calendar"
(click)="datepicker.toggle()"
type="button"
></button>
</div>
</div>
</div>
<div class="form-group ml-2">
<div class="input-group">
<input
#dpToDate
class="form-control"
placeholder="To (YYYY-MM-DD)"
name="dpToDate"
[(ngModel)]="splitRuleDetail.endDate"
[ngModelOptions]="{updateOn: 'blur'}"
(input)="toDate = validateInput(toDate,dpToDate.value)"
/>
<div class="input-group-append">
<button
class="btn btn-outline-secondary calendar"
(click)="datepicker.toggle()"
type="button"
></button>
</div>
</div>
</div>
我已经添加了 TS 文件,这与给定的例子相同。但我认为 ts 文件没有问题。
onDateSelection(date: NgbDate) {
if (!this.fromDate && !this.toDate) {
this.fromDate = date;
} else if (this.fromDate && !this.toDate && date && date.after(this.fromDate)) {
this.toDate = date;
} else {
this.toDate = null;
this.fromDate = date;
}
}
isHovered(date: NgbDate) {
return this.fromDate && !this.toDate && this.hoveredDate && date.after(this.fromDate) && date.before(this.hoveredDate);
}
isInside(date: NgbDate) {
return this.toDate && date.after(this.fromDate) && date.before(this.toDate);
}
isRange(date: NgbDate) {
return date.equals(this.fromDate) || (this.toDate && date.equals(this.toDate)) || this.isInside(date) || this.isHovered(date);
}
validateInput(currentValue: NgbDate | null,input: string): NgbDate | null {
const parsed = this.formatter.parse(input);
return parsed && this.calendar.isValid(NgbDate.from(parsed)) ? NgbDate.from(parsed) : currentValue;
}
解决方法
要遵循的步骤
- 使用
(value)
而不是[(ngModel)]
- 删除
[ngModelOptions]="{updateOn: 'blur'}"
- 在选择日期时手动关闭数据选择器
onDateSelection(date: NgbDate) {
if (!this.fromDate && !this.toDate) {
this.fromDate = date;
} else if (this.fromDate && !this.toDate && date && date.after(this.fromDate)) {
this.toDate = date;
this.sub.close(); // close manually
} else {
this.toDate = null;
this.fromDate = date;
}
}
isHovered(date: NgbDate) {
return this.fromDate && !this.toDate && this.hoveredDate && date.after(this.fromDate) && date.before(this.hoveredDate);
}
isInside(date: NgbDate) {
return this.toDate && date.after(this.fromDate) && date.before(this.toDate);
}
isRange(date: NgbDate) {
return date.equals(this.fromDate) || (this.toDate && date.equals(this.toDate)) || this.isInside(date) || this.isHovered(date);
}
validateInput(currentValue: NgbDate | null,input: string): NgbDate | null {
const parsed = this.formatter.parse(input);
return parsed && this.calendar.isValid(NgbDate.from(parsed)) ? NgbDate.from(parsed) : currentValue;
}