当前位置: 代码迷 >> 综合 >> Ionic 2 添加页面
  详细解决方案

Ionic 2 添加页面

热度:63   发布时间:2023-12-16 08:17:42.0

现在我们已经基本知道了Ionic2 app的布局,接下来我们来走一遍在我们的app里创建和导航页面的过程。

先看看src/app/app.html, 接近底部的地方有如下内容:

<ion-nav id="nav" [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>

注意[root]属性绑定。设置了ion-nav组件的根页面或是第一个基本页面。当加载ion-nav是,rootPage变量引用的就是根页面。

在 src/app/app.component.ts 里, MyApp 组件在它的构造器中定义了他。:

...
import {HelloIonicPage} from '../pages/hello-ionic/hello-ionic';
...export class MyApp {...// make HelloIonicPage the root (or first) pagerootPage: any = HelloIonicPage;pages: Array<{title: string, component: any}>;constructor(private platform: Platform,private menu: MenuController) {...}...
}

我们可以看到rootPage设置为HelloIonicPage,因此HelloIonicPage将会是nav controller中加载的第一个页面。让我们来看一下。

创建页面

接下来我们看看导入的HelloIonicPage 。在 src/pages/hello-ionic/目录下,打开hello-ionic.ts文件。

你可能注意到每个页面有一个目录。在每个目录中还有另外两个同名的.html 和 .scss 文件。例如,在hello-ionic/里面有hello-ionic.ts, hello-ionic.html 和 hello-ionic.scss三个文件。尽管这不是必须的模式,但是这对组织代码很有帮助。

下面,我们看到HelloIonicPage类。这将创建一个页面,提供一个包含所有Ionic指令的Angular组件,加载使用Ionic的导航系统。请注意,因为页面是动态加载,他们没有选择器:

import {Component} from '@angular/core';@Component({templateUrl: 'build/pages/hello-ionic/hello-ionic.html'
})
export class HelloIonicPage {}

所有页面都有一个类,和一个关联的模板的编译。 我们看看 src/pages/hello-ionic/hello-ionic.html - 这个页面的模版文件:

<ion-header><ion-navbar><button menuToggle><ion-icon name="menu"></ion-icon></button><ion-title>Hello Ionic</ion-title></ion-navbar>
</ion-header><ion-content padding class="getting-started"><h3>Welcome to your first Ionic app!</h3><p>This starter project is our way of helping you get a functional app running in record time.</p><p>Follow along on the tutorial section of the Ionic docs!</p><p><button primary menuToggle>Toggle Menu</button></p></ion-content>

<ion-navbar>是这个页面的导航条模版。当我们导航到这个页面,导航条上的按钮和标题作为页面的一部分一起过渡过来。
余下的模版是标准的Ionic代码设置内容区域,打印欢迎信息。

创建附加页面

创建附加页面,我们只需要确保正确设置标题和其他我们希望导航条显示的东西。
我们再来看看src/pages/list/list.ts里面的内容,你会发现定义了一个新的页面:

import {Component} from "@angular/core";
import {NavController, NavParams} from 'ionic-angular';
import {ItemDetailsPage} from '../item-details/item-details';@Component({templateUrl: 'build/pages/list/list.html'
})
export class ListPage {selectedItem: any;icons: string[];items: Array<{title: string, note: string, icon: string}>;constructor(private navCtrl: NavController, navParams: NavParams) {// If we navigated to this page, we will have an item available as a nav paramthis.selectedItem = navParams.get('item');this.icons = ['flask', 'wifi', 'beer', 'football', 'basketball', 'paper-plane','american-football', 'boat', 'bluetooth', 'build'];this.items = [];for(let i = 1; i < 11; i++) {this.items.push({title: 'Item ' + i,note: 'This is item #' + i,icon: this.icons[Math.floor(Math.random() * this.icons.length)]});}}itemTapped(event, item) {this.navCtrl.push(ItemDetailsPage, {item: item});}
}

这个页面创建了一个包含多个数据项的列表页。总之,这个页面和前面的HelloIonicPage 很相似。