angular2-swiper的使用

本文详细介绍了如何在Angular项目中集成Swiper轮播插件,包括安装依赖、配置样式及模块、实现轮播功能等步骤,并附带了事件回调及解决常见错误的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、安装模块

npm install swiper angular2-swiper --save-dev

2、配置angular-cli.json,样式文件

"styles": [ "../node_modules/swiper/dist/css/swiper.css" ],

3、配置app.module.ts

import {KSSwiperModule} from "angular2-swiper"; ... imports: [ KSSwiperModule ], ...

4、模板文件

<div class="myslides">
  <ks-swiper-container [options]="swipeOptions">
    <ks-swiper-slide *ngFor="let item of data">
      <img src="http://api.randomuser.me/portraits/thumb/men/{{item}}.jpg">
    </ks-swiper-slide>
  </ks-swiper-container>
  <button (click)="movePrev()">Prev</button>
  <button (click)="moveNext()">Next</button>
</div>

5、组件

 
  
import {Component, ViewChild, AfterViewInit} from "@angular/core";
import {KSSwiperContainer, KSSwiperSlide} from 'angular2-swiper';
@Component({ selector: "pri-home", templateUrl: "../templates/home.component.html" }) export class HomeComponent { // 单机上一个下一个的时候调用封装子组件中的方法 @ViewChild(KSSwiperContainer) swiperContainer:KSSwiperContainer; // 图片数组 data:Array<number>; // 配置 swipeOptions:any; constructor() { this.swipeOptions = { // 每页显示几张图片 slidesPerView: 4, // 是否循环 loop: false, spaceBetween: 5 }; this.data = [ 1, 2, 3, 4, 5, 6 ] } // 下一个 moveNext() { this.swiperContainer.swiper.slideNext(); } // 上一个 movePrev() { this.swiperContainer.swiper.slidePrev(); } }
 
以上内容转自https://segmentfault.com/a/1190000008611655

6、Event & Callback

在swipeOptions中添加
onSlideChangeEnd: function(swiper){
      alert('事件触发了;');
    }
}

 

注意:

1.ng serve报错

在node_modules找到@angular2-swiper文件夾dist/ks-swiper.module.d.ts添加@NgModule,

ng serve通过
import { NgModule } from "@angular/core"
@NgModule()
export declare class KSSwiperModule {
}

2.ng bulid报错

'ks-swiper-container' is not a known element: 
1. If 'ks-swiper-container' is an Angular component, then verify that it is part of this module. 
2. If 'ks-swiper-container' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
在app.module.ts中添加
    ....
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
    bootstrap: [AppComponent]
})
export class AppModule { }
ng bulid通过

3.必须写在AfterViewInit事件里,否则会有加载错误

转载于:https://www.cnblogs.com/suebuliy/p/7661281.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值