angular 2 owlCarousel不是函数

时间:2017-09-07 06:32:57

标签: jquery angular owl-carousel-2

我试图使用owlcarousel 2和angular 4.我有以下设置:

.angular-cli.json

  "scripts": ["../node_modules/jquery/dist/jquery.js",
                  "../node_modules/tether/dist/js/tether.js",
                  "../node_modules/bootstrap/dist/js/bootstrap.js",
                  "../node_modules/owl.carousel/dist/owl.carousel.js"
                ],

offers-component.ts

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


declare var $: any;

@Component({
  selector: 'home-offers-container',
  templateUrl: '../templates/home-offers-container.template.html',
  styleUrls: ['../css/home-offers-container.component.css']
})

export class HomeOffersContainerComponent implements AfterViewInit {
  ngAfterViewInit() {
    $('.owl-carousel').owlCarousel();
  }
}

template.html

<div class="row">
    <div class="container">
      <home-offers class="owl-carousel"></home-offers>
    </div>
</div>

我收到错误ERROR TypeError: $(...).owlCarousel is not a function。我不明白为什么会出现这个错误。我已按顺序订购了脚本 - 首先是jquery然后是owlcarousel。而且typescritp不会给jQuery带来任何错误。我错过了什么/没有正确加载owlCarousel?

  

我是否必须在app.module.ts中导入jQuery / owlCarousel?如果有,建议如何?

4 个答案:

答案 0 :(得分:0)

而不是直接访问ViewInit中的类

尝试使用 ViewChild ,如

<home-offers class="owl-carousel" #owl></home-offers>

@ViewChild('owl')owl:ElementRef;

  ngAfterViewInit() {
    $(this.owl.nativeElement).owlCarousel();
  }

答案 1 :(得分:0)

使用jQuery进行DOM操作与Angular不是正确的方法。

您可以通过以下方式使用ViewChild装饰器来访问DOM元素:

@Component({
    ....
    templateUrl: 'mytemplate.html'
})

export class MyComponent{
  @ViewChild('selector') private elementName;
  ngAfterViewInit() {
     //this is your dom
     this.elementName.owlCarousel();
  }
}

并在模板类中指定谁是该选择器

<home-offers class="owl-carousel" #selector> </home-offers>

答案 2 :(得分:0)

轮播为我工作了以下变化

  

-从'jquery'导入*作为$;

     

-导入'owl.carousel';

     

+声明var $:any;

其余的组件代码相同

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


declare var $: any;

@Component({
  selector: 'home-offers-container',
  templateUrl: '../templates/home-offers-container.template.html',
  styleUrls: ['../css/home-offers-container.component.css']
})

export class HomeOffersContainerComponent implements AfterViewInit {
  ngAfterViewInit() {
    $('.owl-carousel').owlCarousel();
  }
}

发布此答案以帮助将来的人们。

https://github.com/dereklin/angular-cli-owl-carousel/commit/bd6b30acfee00f60516b541a4da6c5608a2b7b25

答案 3 :(得分:0)

仅需安装此模块 npm install --save-dev @ types / owlcarousel 问候