【问题标题】:Import external .js / .css into angular4 app将外部 .js / .css 导入 angular4 应用程序
【发布时间】:2018-07-05 23:35:40
【问题描述】:

我试图在我的 Angular 应用程序中使用 owl.carousel,这是目标的一个小提琴。

https://owlcarousel2.github.io/OwlCarousel2/demos/mousewheel.html

我采取的步骤是:

  • 从 owl-carousel 网站下载了 zip

  • 将它们粘贴到 ../node_modules/owlCarousel/

  • 不需要在 index.html 上添加 .css 和 .js 文件,因为它是一个内部模块(可以在 node_modules 上找到)

在 angular-cli.json 上,我在脚本中添加了那些 .js 文件的路径

"scripts": [
            "../node_modules/owlCarousel/dist/owl.carousel.js",
            "../node_modules/owlCarousel/dist/owl.carousel.min.js",
....

我在我的菜单组件上使用什么轮播,问题是当我在 ngInit() menu.compontent.ts 上调用函数时:

$(document).ready(function(){
  $(".owl-carousel").owlCarousel();
});

它在 owlCarousel() 上给出一个错误,说“owlCarousel 在类型 'jQuery' 上不存在。

我想在 index.ts 上导出一些我用来导出共享文件夹的所有组件的东西吗?或者我需要在 menu.component.ts 上导入一些东西,如果需要,是什么?

这是我的 menu.compontent.ts:

import { Component, OnInit } from '@angular/core';
//import * as $ from "jquery";
declare var $: any;


@Component({
 selector: 'app-menu',
 templateUrl: './menu.component.html',
 styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit {

 constructor() {
 }
 ngOnInit() {

  $(document).ready(function(){
      $(".owl-carousel").owlCarousel();
  });

  $('#myDropdown').on('hide.bs.dropdown', function () {
      return false;
  });
}

closeNav() {
    document.getElementById("mySidenav").style.width = "0";
}
}

【问题讨论】:

  • declare const $ 并删除导入
  • 我不再有错误,但轮播不起作用..我得到了一堆滑块的图像。开发者工具输出: GET 172.27.192.205:4201/node_modules/owlCarousel/dist/assets/… net::ERR_ABORTED GET 172.27.192.205:4201/node_modules/owlCarousel/dist/… net::ERR_ABORTED core.js:1427 ERROR TypeError: $(...).owlCarousel is not a function
  • 这样不行。您可以在样式[] 内部(node_modules 或其他目录)中包含 CSS,如果它是 CDN,则可以附加到 index.html。
  • 那时我认为它是内部的,因为我已经安装了 owl.carousel "npm install --save owl.carousel" 然后我将它包含在样式 [] 和脚本 [] 以及 angular-cli .json .. 我也有它的索引。我必须删除 .css 和 .js 吗?当它是内部的时,我不必在 index.html 上包含链接和脚本?谢谢你..
  • 在一个地方只包括。否则,您包含的次数与导入的次数一样多。

标签: javascript jquery angular


【解决方案1】:

问题是人们从 Angular 项目开始,不要明白如果没有很好地集成 jQuery 会给你带来问题。这就是为什么人们创建集成这些 jQuery 解决方案的 npm 包的原因。 https://www.npmjs.com/package/angular2-carousel

【讨论】:

    【解决方案2】:

    首先不要同时加载 .js/min.js 和 .css/min.js,因为您正在加载同一事物的 2 个版本。

    其次,您不是在编写打字稿,而是在不必要地用 jquery 污染您的角度。以这种方式使用角度是没有意义的。不建议以这种方式与 DOM 交互

    使用专门为 Angular 编写并遵循 Angular 最佳实践的库,例如。 Ng 引导程序或 NGX 引导程序。否则,只需使用 html 和 jquery 以及您的 owl 库。

    https://ng-bootstrap.github.io/#/components/carousel/examples

    https://valor-software.com/ngx-bootstrap/#/carousel

    【讨论】:

    • 谢谢,我认为我必须导入这两个操作系统。我仍然对如何导入库有点困惑。目标是让滑块像菜单一样执行,一组 8 或 9 个可点击按钮,然后像我给出的示例一样通过单击和拖动滑动到另一组按钮,我认为 owl 有我需要的东西。但是,我仍然需要了解如何以正确的方式导入库,因为我认为我没有按照最佳实践这样做......再次感谢您
    猜你喜欢
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 2017-11-01
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多