一、安装模块css
npm install swiper angular2-swiper --save-dev
二、配置angular-cli.json,样式文件html
"styles": [ "../node_modules/swiper/dist/css/swiper.css" ],
三、配置app.module.tsnode
import {KSSwiperModule} from "angular2-swiper"; ... imports: [ KSSwiperModule ], ...
四、模板文件npm
<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>
五、组件json
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
六、Event & Callbackbootstrap
在swipeOptions中添加
onSlideChangeEnd: function(swiper){ alert('事件触发了;'); } }
注意:
segmentfault
1.ng serve报错api
在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事件里,不然会有加载错误angular2