angular2-swiper的使用
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事件里,否则会有加载错误

浙公网安备 33010602011771号