同一个 Angular app/component 上有几个 Swiper 滑块?

Several Swiper sliders on same Angular app/component?

我使用 Swiper 将滑块添加到我的 Angular (7) 应用程序。

问题是我无法在同一应用程序上设置单独的滑块,即使不在同一组件中也是如此。

Swiper 文档告诉我们,当您将它与 vanilla JS 一起使用时:

var mySwiper = new Swiper('.swiper-container', {
  speed: 400,
  spaceBetween: 100
});

在我的 Angular 应用程序中,我在 .ts 文件中有这个:

import { Component, OnInit, Input } from '@angular/core';
import { ProductItemVM } from 'src/app/models/product/product-item-vm';
import { SwiperConfigInterface } from 'ngx-swiper-wrapper';

@Component({
  selector: 'srp-product-carousel-container',
  templateUrl: './product-carousel-container.component.html',
  styleUrls: ['./product-carousel-container.component.scss']
})

export class ProductCarouselContainerComponent implements OnInit {
@Input() productList: ProductItemVM[];

public config: SwiperConfigInterface = {
direction: 'horizontal',
threshold: 0,
spaceBetween: 20,
slidesPerView: 1,
keyboard: true,
mousewheel: false,
scrollbar: false,
navigation: true,
pagination: true
};

constructor() { }

ngOnInit() {}
}

这里是 doc for Angular wrapper of Swiper.

我不能声明一个新的滑块,所以我不能调用另一个 swiper-container class 来瞄准不同的滑块。

有人遇到过这个问题并找到了解决方法吗? 谢谢。

我们可以使用 ngx-swiper-wrapper

在同一页面或组件上设置多个滑块

如果我们要添加 2 个 carousals/sliders - 一个用于推荐,另一个用于画廊,那么我们需要创建 2 个单独的配置

    import { SwiperConfigInterface } from 'ngx-swiper-wrapper';
    
    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.scss']
    })

    export class HomeComponent implements OnInit {
    
      constructor() { }
    
      ngOnInit(): void {
      }

      gallery_config: SwiperConfigInterface = {
            direction: 'horizontal',
            slidesPerView: 1,
            allowTouchMove: true,
            pagination:{el:'.swiper-pagination',clickable:true},
            autoplay: {
              delay: 3000,
              disableOnInteraction: true
            }
      };
        
      testimonial_config: SwiperConfigInterface = {
            direction: 'horizontal',
            slidesPerView: 3,
            spaceBetween: 40,
            allowTouchMove: true,
            scrollbar:true
      };

现在将配置添加到其各自的 swiper-container。

加gallery_config到一个swiper-container

<div  class="swiper-container" [swiper]="gallery_config" >
        <div class="swiper-wrapper">
          <div  class="swiper-slide">
             ...
          </div>
        </div>
        <div class="swiper-pagination"></div>
</div>
   

将testimonial_config添加到另一个swiper-container

 <div  class="swiper-container" [swiper]="testimonial_config" >
            <div class="swiper-wrapper">
              <div  class="swiper-slide">
                 ...
              </div>
            </div>
            <div class="swiper-pagination"></div>
    </div>

如果您有更多 swiper-container,那么您可以创建更多具有不同名称的配置,如果每个配置具有不同的滑动器样式,则可以将其分配给它们