2017-09-23 87 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