这是一个ionic2-angular2的入门实践。
github:
https://github.com/escawn/ionic2-angular2-tour-of-heroes
在学习angular2的时候,官网用了一个demo:tour-of-heroes来作为例子来讲解一个angular2单页面的结构。地址:(中文版)
https://angular.cn/docs/ts/latest/tutorial/
作为以开发ionic2 app为目标的初学者,在反复看了几遍教程之后,决定自己改写一下这个demo,使他成为一个ionic2的简单demo。
改写步骤
- 新建空白ionic2应用
ionic start tour-of-heroes blank --v2 --ts
blank
表示不使用任何模板
--v2
表示这是一个ionic2应用(而不是ionic)
--ts
表示以typescript为语言基础进行编写
- 按照教程,进行基本的内容填写
找到./app/page/home
,其中ionic2的应用代码都是以页(page)为单位进行编写。home表示一页,虽然名字为home,但实际上app打开的主页面是我们自己定义的,在./app/app.ts
中:
rootPage: any = HomePage;
HomePage
可以改为定义的任何一个page
将home.ts
的内容改为如下:
export class HomePage {
constructor(private navController: NavController) {
}
public title = 'Tour of Heroes';
public hero: Hero = {
id: 1,
name: 'Windstorm',
}
}
export class Hero {
constructor(id: number,
name: string) {
}
}
home.html
改为如下:
{{ title }}
{{ hero.name }} details!
id:
{{ hero.id }}
name:
效果是这样的:
- 创建英雄,添加数据
在home.ts
最后加
const HEROES: Hero[] = [
{ id: 11, name: 'Mr. Nice' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
{ id: 15, name: 'Magneta' },
{ id: 16, name: 'RubberMan' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr IQ' },
{ id: 19, name: 'Magma' },
{ id: 20, name: 'Tornado' }
];
在export class HomePage
内加
public heroes = HEROES;
home.html
部分变成
{{ title }}
My Heroes
{{ hero.id }}
{{ hero.name }}
title
,hero.id
,hero.name
都是我们从hero.ts
中导出,或者说绑定的。
*ngFor
表循环。
ionic2中固定的列表用法。
home.scss
变成(样式调整)
.selected {
background-color: #CFD8DC !important;
color: white;
}
.heroes {
margin: 0 0 2em;
list-style-type: none;
padding: 0;
width: 15em;
}
.heroes ion-item {
cursor: pointer;
position: relative;
left: 0;
background-color: #EEE;
margin: 0.5em;
padding: 0;
height: 1.6em;
border-radius: 4px;
}
.heroes ion-item.selected:hover {
background-color: #BBD8DC !important;
color: white;
}
.heroes ion-item:hover {
color: #607D8B;
background-color: #DDD;
left: 0.1em;
}
.heroes .text {
position: relative;
top: -3px;
}
.heroes .badge {
display: inline-block;
font-size: small;
color: white;
padding: 0.8em 0.7em 0;
background-color: #607D8B;
line-height: 5em;
position: relative;
left: -1px;
top: -4px;
height: 5em;
margin-right: 0.8em;
border-radius: 4px 0 0 4px;
}
【注】:此处部分代码与angular2官方给出的不同,为了达到效果进行了调整。
- 添加click事件
home.ts
里,删除
public hero: Hero = {
id: 1,
name: 'Windstorm',
}
export class HomePage
里增加
public selectedHero: Hero;
onSelect(hero: Hero)
{ this.selectedHero = hero; }
此时home.html
:
My Heroes
{{ hero.id }}
{{ hero.name }}
{{selectedHero.name}} details!
id:
{{selectedHero.id}}
name: