一、安裝模塊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