2017-09-23 141 views
0

我使用的是Angular v.4和Swiper.js,并且我有多个swiper实例的问题。上面的用例: 我认为,我有相同成分的多个实例(滑块细节):角v4和Swiper:同一页上的Swiper的多个实例

<section class="tv-container"> 

    <section *ngIf="creditsTv.cast.length > 0"> 
    <slider-detail [items]="creditsTv.cast" [title]="'Top Billed Cast'" [url]="'/main/tv/wall/popular'"></slider-detail> 
    </section> 

    <section> 
    <slider-detail [items]="similarTv.results" [title]="'Similar'" [url]="'/main/tv/wall/popular'"></slider-detail> 
    </section> 

    <section *ngIf="recommendationsTv.results.length > 0"> 
    <slider-detail [items]="recommendationsTv.results" [title]="'Recommendations'" [url]="'/main/tv/wall/popular'"></slider-detail> 
    </section> 

</section> 

,这是我滑盖detail.component.html组分:

<section class="list-section"> 
    <h1 class="title-section"> 
    {{title}} 
    </h1> 
    <div class="swiper-container"> 
    <div class="swiper-wrapper"> 
     <div class="swiper-slide" *ngFor="let item of items"> 
      <slide-credit [item]="item"></slide-credit> 
     </div> 
    </div> 
    <div class="swiper-button-prev swiper-button-white"></div> 
    <div class="swiper-button-next swiper-button-white"></div> 
    </div> 
</section> 

,这是我滑盖detail.component.ts组件:

import { Component, Input, OnInit, AfterViewInit, ChangeDetectionStrategy, OnDestroy } from '@angular/core'; 

@Component({ 
    selector: 'slider-detail', 
    templateUrl: './slider-detail.component.html', 
    styleUrls: ['./slider-detail.component.scss'], 
    changeDetection: ChangeDetectionStrategy.OnPush 
}) 
export class SliderDetailComponent implements OnInit, OnDestroy { 

    @Input() items: any; 
    @Input() title: string; 
    @Input() url: string; 

    private _swiper: any; 

    constructor() { } 

    ngOnInit() { 
    } 

    ngAfterViewInit() { 
    // Initialize Swiper 
    this._swiper = new Swiper('.swiper-container', { 
     initialSlide: 0, 
     direction: "horizontal", 
     slidesPerView: "auto", 
     slidesPerGroup: 2, 
     nextButton: '.swiper-button-next', 
     prevButton: '.swiper-button-prev', 
     slidesOffsetBefore: 0, 
     slidesOffsetAfter: 0, 
     observer: true, 
     observeParents: true 
    }); 
    } 

    ngOnDestroy() { 
    // this._swiper.update(true); 
    this._swiper.destroy(); 
    } 

} 

现在,当改变路线,我要摧毁(ngOnDestroy())的this._swiper,但我得到这个错误:如果我打印this._swiper之前this._swiper.destroy(

this._swiper.destroy is not a function

) ,我有一个swiper实例的数组。 所以要销毁实例我必须做这个._swiper [index] .destroy()但我没有索引。

我该如何解决?你有另外的解决方案吗? 我可以将实例包装到类中而不是全局吗?

谢谢!

回答

0

在添加新的swiper对象之前,请获取当前swiper实例数组的长度。这应该是你的索引。

let index: number = this._swiper.length - 1; 
if (index < 0) { 
    index = 0; 
} 
+0

不幸的是没有工作。如果我添加你的代码并且打印完索引后,我总是获得index = 0。 – Ragnarr