angular - 无法读取未定义 Angular 的属性“ngbDateParserFormatter”
问题描述
在输入字段的自定义验证函数中,我使用 ngbDateParserFormatter 将 ngBootstrap 日期对象转换为普通日期格式。
但是在转换时它不断出错
无法读取未定义的属性“ngbDateParserFormatter”
我ngbDateParserFormatter
之前在该文件中的几个地方使用过,并且工作正常。
我的验证码:-
export class ApplyLeaveComponent {
constructor(
private panelService: PanelService,
private router: Router,
private fb: FormBuilder,
private ngbDateParserFormatter: NgbDateParserFormatter,
private toastr: ToastrService
) {}
ngOnInit() {}
applyLeave(data) {
if (this.totalLeave - this.availedLeaves.length <= 0) {
this.toastr.error("", "No Remaining Leaves", { positionClass: "toast- bottom-right" });
} else {
this.submitted = true;
if (this.leaveForm.invalid) {
return;
} else {
var leaveData = {
financialYear: this.financialYear.id,
profileId: this.userDetails.profileId,
emailFrom: this.userDetails.email,
leaveFromDate: this.ngbDateParserFormatter.format(data.value.leaveFromDate),
leaveToDate: this.ngbDateParserFormatter.format(data.value.leaveToDate),
leaveType: data.value.leaveType,
leaveReason: data.value.leaveReason,
notifyPerson: data.value.notifyPerson,
reportingPerson: data.value.reportingPerson
};
this.applyLeaveService.SaveLeave(leaveData).subscribe(
res => {
console.log(res);
this.leaveForm.reset();
this.submitted = false;
this.toastr.success("", "Leave applied Successfully", {
positionClass: "toast-bottom-right"
});
},
err => {
console.log(err);
this.toastr.error("", "Error on Applying", { positionClass: "toast-bottom-right" });
}
);
}
}
}
dateValidation(control: AbstractControl): { [key: string]: any } | null {
var currentvalue = control.value;
console.log(currentvalue);
var selectedDate = this.ngbDateParserFormatter.format(currentvalue);
let dateFormat = require("dateformat");
let now = new Date();
var today = dateFormat(now, "dd mm yyyy");
console.log(today);
return null;
}
}
control.value
是一个有值的日期对象{year: 2019, month: 6, day: 6}
谁能解决?
解决方案
我不知道dateValidation
您的代码中究竟在哪里使用,但要修复该错误,您需要绑定this
到您的自定义验证器,dateValidation
. 这是因为该dateValidation
方法的上下文在被 Reactive Form 调用时FormControl
没有引用到您的 main ApplyLeaveComponent
。
例如,您可以通过执行以下操作this
来绑定:dateValidation
yourForm = this.fb.group({
leaveFromDate: [null, [this.dateValidation.bind(this)]],
});
推荐阅读
- reactjs - 来自 GraphQL 的动态数据的材质 UI 卡渲染问题
- javascript - 使用 JS 查找字段并从中生成对象
- arduino - arduino中的动态数组声明
- python - 为什么我的电脑不能运行从 sympy 导入的 Python 程序
- javascript - 未存储 URL 的 React Firestore 图像数组
- git - git push --mirror 和 git set-url 的区别
- sql - 根据线串的 id 创建 Polygon / MultiLineString
- c# - C# - 构建谓词时调用私有函数不起作用
- c# - 如何使用 2 个类作为泛型方法的参数
- javascript - 如何将值传递给 Ionic/Angular 中的按钮?