ionic 学习笔记:轮播图、导航与传值、CSS 圆角图片、ngFor、表达式的使用

644 阅读2分钟

轮播图

轮播图的 html:

<ion-slides paper="true" [options]="slideOpts">
    <ion-slide>
        <img src="">
    </ion-slide>
    <ion-slide>
        <img src="">
    </ion-slide>
</ion-slides>

需要注意,虽然只有 html 也能够显示出来轮播图,但实际上这样的轮播图是不完整的。

如果想要对其添加更多的效果、应用更多的功能,则需要在页面对应的脚本中使用代码进行配置和控制,如下,相对应的 ts:

import { IonSlides } from '@ionic/angular';

export class HomePage {
    @ViewChild(IonSlides) slides: IonSlides;	// 声明轮播图对象
    slideOpts = {			// 给轮播图的参数,这里和上面 html 中的 [options] 相对应
        initialSlide: 0,
        speed: 200
    };
    // 如果想要在一开始就让轮播图自动播放
    ionViewDidEnter() {
        console.log(this.slides);
        this.slides.startAutoplay();
    }
}

关于轮播图,ionicframework.com 中的文档叙述的比较简略,更多的详细说明可见:www.idangero.us/swiper/

import { Router } from '@angular/router';
constructor(private router: Router){
    this.pageCotentList=[{       //内容List,在其中进行插入内容并排序,方便调用
        title: "",
        subtitle: "",
        id: 0     //计算机中计数一般从0开始
    },{
        title: "",
        subtitle: "",
        id: 1
    }];
}
goToStore(selectedId: any){
    this.router.navigate(['page1'],{  //跳转到page1页面
        queryParams: {
            selectedId: selectedId    //将page1页面的值传递给selectedId
        }
    });
}

以上是ts中的对应脚本。

html中:

<ion-list>
    <ion-item *ngFor="let news of pageContentList" (click)="goToStore(news.id)">
        <ion-thumbnail slot="end">  <!--图片边框是方形,且居右("end")-->
            <img src={{news.imgUrl}}>   <!--调用ts中pageContentList中的imgUrl部分-->
        </ion-thumbnail>
        <ion-label>
            <h2>{{news.title}}</h2>
            <h3>{{news.subtitle}}</h3>
            <p>{{news.content}}</p>
        </ion-label>
    </ion-item>
</ion-list>

利用ts中排序列项内容,再在html中进行调用,在进行重复相似页面编辑中可以省很多事,类似于只需要进行内容填充,再调用即可产生不一样的页面。

CSS 圆角图片

.roundedSquareImg {
  border-radius: 50px;   //圆角大小
  width: 100%;
}

以上为给图片添加圆角在scss中的函数。

html中调用

<img class="roundedSquareImg" src="">  <!--必须要将class写在前面,否则无法实现圆角-->

ngFor 的用法

<ion-item *ngFor="let news of pageContentLits" (click)="goToStore(news.id)">
    <!--ngFor用法如上,类似于将pageContentList中的每个元素写作news来引用(自我理解:简化作用)-->
    <ion-label>
        <p>
            {{news.content}}  <!--content本来是pageContentList名下的元素,现在可以用news引用-->
        </p>
    </ion-label>
</ion-item>

表达式的使用 {{}}

在 html 中,双花括号 {{}} 中的内容会被 Angular 作为表达式来进行解析,而不是直接作为字符串进行显示。

例如:{{ 1+1 }} ,会被直接显示为 2

又例如,在双花括号中写上页面对应 ts 中的变量名,则会被显示为变量值:

image-20210313195541632.png

image-20210313195551760.png

则,会被显示为:

image-20210313195605705.png