.modal() 函数在 angular 8 中不起作用

.modal() function not working in angular 8

单击时,"$("#Popup").modal('show')" 不起作用。

HTML

<a class="btn-profile-login" data-target="#Popup" (click)="loginBtn()">{{SignText}}</a>

TS

import { Component, OnInit, ViewChild } from '@angular/core';
import * as $ from 'jquery';
import * as bootstrap from "bootstrap"; 

export class SampleComponent implements OnInit{
    loginBtn() {
        $("#Popup").modal('show');
    }
}

错误信息:

TypeError: jquery__WEBPACK_IMPORTED_MODULE_9__(...).modal is not a function

您需要在 index.html 中包含 jQuery,在您的 component 中您需要

declare var $: any;

您可以按照以下步骤操作

npm install jquery --save
npm install @types/jquery --save

然后在 architect 的脚本部分 => 构建 angular.json 文件,我们为 jquery lib

添加路径
"scripts": [
  "node_modules/jquery/dist/jquery.min.js"
]

然后修改tsconfig.app.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": ["jquery"] // addd jquery here
  },
  "exclude": ["test.ts", "**/*.spec.ts"]
}

然后你可以删除这个导入,因为你已经有了 jquery

的类型定义
import * as $ from 'jquery';

使用ngx-bootstrap https://valor-software.com/ngx-bootstrap/是AngularBootstrap个不需要jQuery的组件。这是将 Bootstrap 与 Angular 一起使用的官方方式,您应该尽可能避免在 angular 应用程序中包含 jquery

祝一切顺利。

"scripts": [ "node_modules/bootstrap/dist/js/bootstrap.min.js" ]

这对我有用 angular.json