поскольку я новичок в angular2, я ожидаю найти решение для следующего сценария. Плагин jQuery не работает после получения данных - http://www.owlcarousel.owlgraphic.com/
Я получил проблемы на * var owl = jQuery (this.elementRef.nativeElement).find('# breif'); owl.owlCarousel();
Мой полный код приведен ниже
угловой компонент 2:
/ beautify ignore:start /
import {Component, OnInit , ElementRef, Inject } from '@angular/core';
import {FORM_DIRECTIVES} from '@angular/common';
import {CAROUSEL_DIRECTIVES} from 'ng2-bootstrap/components/carousel';
/ beautify ignore:end /
import {Api} from '../../../../services/api';
declare var jQuery:any;
@Component({
selector: 'breif',
directives: [CAROUSEL_DIRECTIVES],
template: require('./template.html')
})
export class BreifComponent implements OnInit {
elementRef: ElementRef;
breifs: Object;
public myInterval:number = 5000;
public noWrapSlides:boolean = false;
public slides:Array<any> = [];
constructor(@Inject(ElementRef) elementRef: ElementRef , private api: Api) {
this.elementRef = elementRef
this.loadBreif();
}
ngOnInit() {
**var owl = jQuery(this.elementRef.nativeElement).find('#breif');
owl.owlCarousel();**
}
loadBreif(){
this.api.getBreif().subscribe(
data => {
this.breifs = data.result.articles;
},
err => console.error(err),
() => {
}
)
}
}
template.html
<div class="owl-carousel" id="breif" >
<div class="item" *ngFor="let breif of breifs"><h4>{{breif.title}}</h4></div>
Привет, я опубликовал обходной путь использования [email protected] с угловым 2.0.0 + webpack + [email protected].
Некоторые из проблем, с которыми я столкнулся, были с плагином jQuery.
Пожалуйста, будьте более конкретными об исключении/ошибке...
Сначала U'll нужно будет установить вышеуказанные пакеты через npm или аналогичные. Затем → npm install import-loader (для использования owl внутри компонента, иначе u'll get fn не определено... так как сторонние модули полагаются на глобальные переменные типа $ или это объект окна...).
Если вы используете WebPack:
импорт-загрузчик следующим образом:
{test: /bootstrap\/dist\/js\/umd\//, loader: 'imports?jQuery=jquery'}
Также вы можете использовать jQuery с webpack:
var ProvidePlugin = require('webpack/lib/ProvidePlugin');
В разделе плагина webpack.common.js:
plugins: [
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery',
'window.jQuery': 'jquery'
})
]
Для загрузчика изображений:
{
test: /\.(png|jpe?g|gif|ico)$/,
loader: 'file?name=public/img/[name].[hash].[ext]'
}
* public/img - папка с изображениями
Загрузчик CSS:
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw'
}
Файл vendors.js должен импортировать следующее:
import 'jquery';
import 'owl.carousel';
import 'owl.carousel/dist/assets/owl.carousel.min.css';
Помните, что owl.carousel 2 по-прежнему использует andSelf() устаревшую функцию jQuery, поэтому нам нужно заменить их на новую версию addBack().
Перейти к папке node_modules в пакете сова dist/owl.carousel.js: заменить все вхождения andSelf() на → addBack().
Теперь угловая 2 часть:
Сова-carousel.ts:
import {Component} from '@angular/core';
@Component({
selector: 'carousel',
templateUrl: 'carousel.component.html',
styleUrls: ['carousel.css']
})
export class Carousel {
images: Array<string> = new Array(10);
baseUrl: string = './../../../../public/img/650x350/';
}
carousel.component.ts:
import { Component, Input, ElementRef, AfterViewInit, OnDestroy } from '@angular/core';
@Component({
selector: 'owl-carousel',
template: '<ng-content></ng-content>'
})
export class OwlCarousel implements OnDestroy, AfterViewInit{
@Input() options: Object;
$owlElement: any;
defaultOptions: Object = {};
constructor(private el: ElementRef) {}
ngAfterViewInit() {
for (var key in this.options) {
this.defaultOptions[key] = this.options[key];
}
var temp :any;
temp = $(this.el.nativeElement);
this.$owlElement = temp.owlCarousel(this.defaultOptions);
}
ngOnDestroy() {
this.$owlElement.data('owlCarousel').destroy();
this.$owlElement = null;
}
}
carousel.component.html:
<owl-carousel class="owl-carousel"[options]="{navigation: true, pagination: true, rewindNav : true, items:2, autoplayHoverPause: true, URLhashListener:true}">
<div class="owl-stage" *ngFor="let img of images; let i=index">
<div class="owl-item">
<a href="#"><img src="{{baseUrl}}{{i+1}}.png"/></a>
</div>
</div>
</owl-carousel>
Обязательно загрузите все в app.module:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import {OwlCarousel} from './components/carousel/carousel.component';
import {Carousel} from './components/carousel/owl-carousel';
@NgModule({
imports: [
BrowserModule,
NgbModule,
],
declarations: [
AppComponent,
OwlCarousel,
Carousel
],
providers: [appRoutingProviders],
bootstrap: [ AppComponent ]
})
export class AppModule { }