无法读取未定义Angular的属性'ngbDateParserFormatter'

时间:2019-06-26 11:38:29

标签: angular angular7

使用输入字段的自定义验证功能,使用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;
  }
}

intellisence values on <code>this</code>

control.value是具有值{year: 2019, month: 6, day: 6}的日期对象

任何人都可以解决吗?

1 个答案:

答案 0 :(得分:1)

我不知道代码中dateValidation的确切位置,但是要解决该错误,您需要将this绑定到自定义验证器dateValidation上。这是因为dateValidation方法的上下文在被反应式表单FormControl调用时未引用到您的主ApplyLeaveComponent

例如,您可以通过执行以下操作将this绑定到dateValidation

yourForm = this.fb.group({
  leaveFromDate: [null, [this.dateValidation.bind(this)]],
});