How to use owl-carousel in Angular2?
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: `
<h2>Sample 1</h2>
<owl-carousel [options]="{navigation: true, pagination: false, rewindNav : false}">
<div *ngFor="#item of items1">
<p>{{ item }}</p>
</div>
</owl-carousel>
<h2>Sample 2</h2>
<owl-carousel [options]="{navigation: false, pagination: true, rewindNav : false}">
<div *ngFor="#item of items2">
<p>{{ item }}</p>
</div>
</owl-carousel>
<h2>Sample 3</h2>
<owl-carousel [options]="{navigation: false, pagination: true, rewindNav : false}">
<div *ngFor="#img of images">
<img src="http://lorempixel.com/400/200/{{img}}"/>
</div>
</owl-carousel>`
})
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: `<ng-content></ng-content>`
})
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
The above does not work for owl2 because the library expects the class attribute:
e.g. see this code in owl2:
if (settings.responsiveClass) {
this.$element.attr('class',
this.$element.attr('class').replace(
new RegExp('(' +this.options.responsiveClass + '-)\\S+\\s', 'g'),
'$1' + match));
make sure to include the class attribute in the element.