You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 12调用外部JS报错:hijriDatePicker不是函数

解决Angular中引入bootstrap-hijri-datepicker的"fn.hijriDatePicker is not a function"错误

问题原因分析

出现该错误的核心原因是插件未正确挂载到jQuery对象,或初始化逻辑存在问题:

  • 组件内局部引入的$与插件挂载的全局jQuery对象不统一
  • 每次点击调用$(document).ready,但该事件仅在页面首次加载时触发,后续点击的回调不会执行,导致初始化失效
  • 依赖加载顺序错误,插件在jQuery或Bootstrap之前加载

解决方案

1. 确保依赖正确安装与全局配置

先确认已安装jQuery和Bootstrap(未安装则执行命令):

npm install jquery bootstrap --save

在angular.json中配置全局依赖,严格遵循jQuery → Bootstrap → 日期插件的加载顺序:

{
  "architect": {
    "build": {
      "options": {
        "styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          // 若插件有配套样式,添加对应路径,比如assets/css/bootstrap-hijri-datetimepicker.css
        ],
        "scripts": [
          "node_modules/jquery/dist/jquery.min.js",
          "node_modules/bootstrap/dist/js/bootstrap.min.js",
          "assets/js/bootstrap-hijri-datetimepicker.js"
        ]
      }
    }
  }
}

2. 调整组件代码,正确初始化插件

移除组件内的局部$引入,改用全局jQuery对象,并在视图初始化完成后一次性初始化插件:

import { Component, AfterViewInit } from '@angular/core';

// 声明全局jQuery,避免TypeScript类型报错
declare var $: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {

  ngAfterViewInit(): void {
    // 视图渲染完成后初始化日期选择器
    $("#hijri-picker").hijriDatePicker({
      hijri: true,
      showSwitcher: false,
    });
  }
}

3. 简化模板代码

插件会自动绑定输入框的交互事件,无需手动绑定click事件:

<input id="hijri-picker" type="text" class="form-control" />

额外注意事项

  • 确认插件文件路径正确,确保assets/js/bootstrap-hijri-datetimepicker.js存在
  • 若仍有问题,检查浏览器控制台是否有其他依赖加载错误,比如Bootstrap未正确加载

内容的提问来源于stack exchange,提问作者sridharan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 09:01:17