You need to enable JavaScript to run this app. Angular10 ng-bootstrap日期选择器自定义格式化报模块未找到错误
优惠活动
大模型
产品
解决方案
定价
更多

Angular10 ng-bootstrap日期选择器自定义格式化报模块未找到错误

Angular 10 + ng-bootstrap 日期选择器自定义格式报错解决方案

报错根因

  • 匹配Angular 10的ng-bootstrap 8.x版本已经废弃并移除了旧的内部工具导入路径@ng-bootstrap/ng-bootstrap/util/util,从这个路径导入isNumber、padNumber、toInteger工具函数时,会直接触发模块找不到的编译报错。上述三个工具函数在当前兼容版本下的导出路径已经迁移到@ng-bootstrap/ng-bootstrap/util/date-adapter下。
  • 现有自定义服务的格式化逻辑和目标需求不匹配:原代码的format方法返回的是斜杠分隔的dd/mm/yyyy格式,并非需要的横杠分隔dd-mm-yyyy格式。

修复操作

1. 修正工具函数的导入路径

将服务文件中原有的错误导入:
import { isNumber, padNumber, toInteger } from '@ng-bootstrap/ng-bootstrap/util/util';
替换为当前兼容版本下的正确导入路径:
import { isNumber, padNumber, toInteger } from '@ng-bootstrap/ng-bootstrap/util/date-adapter';

2. 调整服务实现适配目标格式

修正后的完整CustomDateFormatterService代码如下,实现严格匹配dd-mm-yyyy的解析和显示规则:

import { Injectable } from '@angular/core';
import { NgbDateParserFormatter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { isNumber, padNumber, toInteger } from '@ng-bootstrap/ng-bootstrap/util/date-adapter';

@Injectable()
export class CustomDateFormatterService extends NgbDateParserFormatter {
  parse(value: string): NgbDateStruct {
    if (!value) return null;
    const dateParts = value.trim().split('-');
    if (dateParts.length === 1 && isNumber(dateParts[0])) {
      return {day: toInteger(dateParts[0]), month: null, year: null};
    }
    if (dateParts.length === 2 && isNumber(dateParts[0]) && isNumber(dateParts[1])) {
      return {day: toInteger(dateParts[0]), month: toInteger(dateParts[1]), year: null};
    }
    if (dateParts.length === 3 && isNumber(dateParts[0]) && isNumber(dateParts[1]) && isNumber(dateParts[2])) {
      return {day: toInteger(dateParts[0]), month: toInteger(dateParts[1]), year: toInteger(dateParts[2])};
    }
    return null;
  }
  
  format(date: NgbDateStruct): string {
    if (!date) return '';
    const day = isNumber(date.day) ? padNumber(date.day) : '';
    const month = isNumber(date.month) ? padNumber(date.month) : '';
    return `${day}-${month}-${date.year}`;
  }
}

3. 无需修改Core Module的注册逻辑

在Core Module的providers中,通过{ provide: NgbDateParserFormatter, useClass: CustomDateFormatterService }将自定义服务绑定到ng-bootstrap的日期格式化令牌上的写法完全正确,只要服务本身可以正常编译,全局所有使用ng-bootstrap日期选择器的组件都会自动应用这套自定义规则。

补充提示:如果修正路径后仍有导入报错,请检查项目中安装的ng-bootstrap版本是否和Angular 10兼容。Angular 10官方适配的ng-bootstrap版本范围为7.1.x ~ 8.0.x,过高版本的ng-bootstrap(如10.x及以上)既不支持当前Angular版本,工具函数的导出路径也会再次变更,不适合本项目使用。


内容的提问来源于stack exchange,提问作者mnu-nasir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.10 12:45:03