ionic2中ion-slides轮播图报错Uncaught TypeError: Cannot read property 'hasAttribute' of undefined

时间:2022-12-25 22:59:18

在使用ionic2的轮播图时会报错:

Uncaught TypeError: Cannot read property 'hasAttribute' of undefined
    at autoplay (swiper.js:175)
    at startAutoplay (swiper.js:218)
    at initSwiper (swiper.js:164)
    at Slides._initSlides (slides.js:828)
    at slides.js:527
    at SafeSubscriber.schedulerFn [as _next] (core.es5.js:3863)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
    at SafeSubscriber.next (Subscriber.js:185)
    at Subscriber._next (Subscriber.js:125)
    at Subscriber.next (Subscriber.js:89)

解决方法:

加一个判断,判断轮播的数组有值再显示

注意判断轮播数组的长度的时候会出现length属性未定义的报错,这是由于页面加载的时候模板先加载了,componnent还没有加载,就没有渲染模板之前模板就加载了导致模板加载的时候没有读取到轮播数组,所以会报错,解决方法:

在component里面定义一个参数,在获取到轮播数组的时候就获取该数组的长度值赋给这个参数,然后在模板里面用这个参数去做判断;

定义参数获取当前轮播数组长度

this.len=this.list.length;
判断
*ngIf="len >=1"

<ion-slides class="slide"  [pager]="true" [loop]="true" autoplay="3000" *ngIf="len >=1" >
    <ion-slide *ngFor="let slide of list" >
        <a href="{{slide.LinkUrl}}" (click)="bannerDetail(slide)">
            <img src="{{slide.PicUrl}}">
        </a>
        <div class="slidesTitle">
            <div class="iteming">
                <span class="title">{{slide.Title}}</span>
            </div>
        </div>
    </ion-slide>
</ion-slides>