How to use owl-carousel in Angular2?

后端 未结 2 1011
春和景丽
春和景丽 2020-12-02 01:16

I am new to Angular2 and was trying to convert owl-carousel in Angularjs to Angular2.

Below is the index.html file for the owl-carousel implementation:



        
2条回答
  •  悲哀的现实
    2020-12-02 01:31

    Update

    OwlCarousel2 + Angular2.3.0

    ngOnDestroy() {
      this.$owlElement.owlCarousel('destroy');
      this.$owlElement = null;
    }
    

    Old version

    Below is the app.ts file for the angular2 owl-carousel implementation:

    import {Component} from 'angular2/core';
    import { OwlCarousel } from './owl-carousel.component';
    
    @Component({
      selector: 'app',
      directives: [OwlCarousel],
      template: `
        

    Sample 1

    {{ item }}

    Sample 2

    {{ item }}

    Sample 3

    ` }) export class App { items1: array = [1, 2, 3, 4, 5]; items2: array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; images: array = ['sports', 'abstract', 'people', 'transport', 'city', 'technics', 'nightlife', 'animals']; }

    owl-carousel.component.ts

    import { Component, Input, ElementRef } from 'angular2/core';
    import $ from 'jquery';
    import 'owl-carousel';
    
    @Component({
      selector: 'owl-carousel',
      template: ``
    })
    export class OwlCarousel {
      @Input() options: object;
    
      $owlElement: any;
    
      defaultOptions: object = {};
    
      constructor(private el: ElementRef) {}
    
      ngAfterViewInit() {
        for (var key in this.options) {
          this.defaultOptions[key] = this.options[key];
        }
        this.$owlElement = $(this.el.nativeElement).owlCarousel(this.defaultOptions);
      }
    
      ngOnDestroy() {
        this.$owlElement.data('owlCarousel').destroy();
        this.$owlElement = null;
      }
    }
    

    Full example you can see in plunker

    OwlCarousel2 version is here https://plnkr.co/edit/FnZVxB?p=preview

提交回复
热议问题