Angular 5项目中bootstrap-datepicker导入方法咨询(使用Angular CLI)
嘿,我来帮你梳理清楚在Angular 5项目里用bootstrap-datepicker的正确姿势,按下面的步骤操作就能搞定啦:
1. 先确认依赖安装到位
首先得确保你已经通过npm装好了bootstrap-datepicker,要是还没装,跑这个命令:
npm install bootstrap-datepicker --save
另外,你已经在angular-cli.json里加了jQuery和Bootstrap的脚本,记得这俩也得是通过npm安装的(不然路径容易出问题)。
2. 完善angular-cli.json的配置
你已经配置了部分脚本,但还得把bootstrap-datepicker的JS和CSS都加进去:
- 在
scripts数组里追加datepicker的JS文件路径:
"scripts": [ "../node_modules/jquery/dist/jquery.js", "../node_modules/popper.js/dist/umd/popper.js", "../node_modules/bootstrap/dist/js/bootstrap.js", "../node_modules/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js", "../js/custom.js" ]
- 别忘了在
styles数组里加datepicker的样式文件,不然界面会乱:
"styles": [ "../node_modules/bootstrap/dist/css/bootstrap.min.css", "../node_modules/bootstrap-datepicker/dist/css/bootstrap-datepicker3.min.css", "styles.css" ]
3. 解决TypeScript的类型报错
因为Angular用的是TypeScript,直接用$会提示找不到变量,有两种解决方式:
- 简单粗暴版:在你要使用datepicker的组件顶部加一行声明:
declare var $: any;
- 优雅规范版:安装对应的类型定义包,这样TS能识别jQuery和datepicker的类型:
npm install @types/jquery @types/bootstrap-datepicker --save-dev
4. 在组件里初始化datepicker
bootstrap-datepicker是基于jQuery的插件,不是Angular组件,所以得在DOM渲染完成后用jQuery初始化。推荐在ngAfterViewInit钩子函数里操作:
import { Component, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-date-picker', template: `<input type="text" class="form-control date-picker-input" placeholder="请选择日期">` }) export class DatePickerComponent implements AfterViewInit { ngAfterViewInit(): void { // 初始化datepicker,还可以加自定义配置 $('.date-picker-input').datepicker({ format: 'yyyy-mm-dd', autoclose: true, todayHighlight: true }); } }
几个关键注意点
- 一定要保证jQuery在bootstrap-datepicker之前加载,不然插件会找不到依赖
- Angular 5用的是
angular-cli.json(Angular 6+才是angular.json),路径要对应正确,../node_modules是相对于src文件夹的,没问题 - 别试图用
import导入bootstrap-datepicker,它不是Angular组件,只能通过全局脚本加载后用jQuery调用
内容的提问来源于stack exchange,提问作者BigBytes
相关产品推荐
相关产品推荐

