【发布时间】:2018-03-04 20:52:42
【问题描述】:
我正在使用 Angular v.4 和 Swiper.js,但我遇到了多个 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>
这是我的 slider-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>
这是我的 slider-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.destroy 不是函数
如果我在 this._swiper.destroy() 之前打印 this._swiper,我有一个 swiper 实例数组。 所以要销毁实例,我必须这样做。_swiper[index].destroy() 但我没有索引。
我该如何解决?你有其他解决方案吗? 我可以将实例包装到类而不是全局吗?
谢谢!
【问题讨论】:
标签: angular typescript ionic-framework ionic3 swiper