Contents
สร้างแอพ Ionic ด้วยคำสั่ง
[code]
> ionic start myApp blank
[/code]
แก้ไขไฟล์ src/pages/home/home.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { contacts: any[]; constructor(public navCtrl: NavController) { } ionViewDidLoad() { this.loadcontacts(); } loadcontacts() { this.contacts = [ { title: 'AAA', contact: '111' }, { title: 'BBB', contact: '222' }, { title: 'CCC', contact: '333' }, { title: 'DDD', contact: '444' } ] } } |
บรรทัดที่ 10 : สร้างตัวแปร contacts
บรรทัดที่ 17 : เมื่อโหลดวิวเสร็จ ให้เรียกเมธอด loadcontacts()
บรรทัดที่ 21-26 : กำหนดค่าให้กับตัวแปร contacts
แก้ไขไฟล์ src/pages/home/home.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<ion-header> <ion-navbar> <ion-title> Ionic Blank </ion-title> </ion-navbar> </ion-header> <ion-content padding> <ion-list> <ion-item *ngFor="let contact of contacts"> {{contact.title}} {{contact.contact}} </ion-item> </ion-list> </ion-content> |
บรรทัดที่ 10 : แสดงลิสต์
บรรทัดที่ 11 : กำหนดให้ไอเทมที่จะแสดงในลิสต์นำค่ามาจากตัวแปร contacts
บรรทัดที่ 12 : แสดงค่าตัวแปร contact.title
บรรทัดที่ 12 : แสดงค่าตัวแปร contact.contact
แสดงแค่ item แรก
src/pages/home/home.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { contacts: any[]; title: any; constructor(public navCtrl: NavController) { } ionViewDidLoad() { this.loadcontacts(); } loadcontacts() { this.contacts = [ { title: 'AAA', contact: '111' }, { title: 'BBB', contact: '222' }, { title: 'CCC', contact: '333' }, { title: 'DDD', contact: '444' } ] this.title = this.contacts[0].title; } } |
src/pages/home/home.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<ion-header> <ion-navbar> <ion-title> Ionic Blank </ion-title> </ion-navbar> </ion-header> <ion-content padding> First item is {{title}} <ion-list> <ion-item *ngFor="let contact of contacts"> {{contact.title}} {{contact.contact}} </ion-item> </ion-list> </ion-content> |
แสดงรายการแบบ reverse
1 2 3 |
<li *ngFor="user of users?.reverse()"> {{ user.name }} is {{ user.age }} years old. </li> |
Link