This small tutorial explains how to pre-render or pre-populate the data in the form in ionic 2. Mostly we do this while editing form.
I am using typscript and Ionic 2 framework. I am considering you already having project setup.
Cordova CLI: 6.4.0
Ionic Framework Version: 2.0.0-rc.0
Ionic CLI Version: 2.1.7
Ionic App Lib Version: 2.1.4
Ionic App Scripts Version: 0.0.30
OS: Linux 3.13
Node Version: v6.6.0
Lets say, you want to create the contact form with name and contact number fields.
contact/
contact.html
contact.ts
contact.scss
Your HTML file should be something like this.
<form #contactsForm="ngForm" novalidate autocomplete="false"> <ion-item> <ion-label stacked>Contact Name</ion-label> <ion-input [(ngModel)]="contact.name" name="contact_name" type="text" #name="ngModel" spellcheck="false" autocapitalize="off" required> </ion-input> </ion-item> <p [hidden]="name.valid || submitted == false" color="danger" padding-left> Contact name can't be empty! </p> <ion-item> <ion-label stacked>Contact Number </ion-label> <ion-input [(ngModel)]="contact.mobile" name="contact_mobile" type="text" #mobile="ngModel" spellcheck="false" autocapitalize="off" required> </ion-input> <ion-icon name="contact" (click)="pickContact()" icon-right item-right></ion-icon> </ion-item> <p [hidden]="mobile.valid || submitted == false" color="danger" padding-left> Contact number can't be empty! </p> <ion-row responsive-sm> <ion-col> <button ion-button (click)="onSave(contactsForm)" type="submit" color="secondary" block>Save Contact</button> </ion-col> </ion-row> </form>
Typescript file (contact.ts)
import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { UserData } from '../../providers/user-data'; @Component({ selector: 'page-contact', templateUrl: 'contact.html' }) export class ContactPage { submitted = false; contact: { name?: string, mobile?:string, id?:string, message?:string } = {name:'',mobile:'',id:''}; constructor( public navCtrl: NavController, public userData: UserData ) { } ionViewDidLoad() { this.userData.contact().then((contact) => { this.contact = JSON.parse(contact); // this will bind the data to the view }); }
Provider file user-data.ts
import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; @Injectable() export class UserData { constructor( public storage: Storage, ) {} setContact(contact) { this.storage.set('contact', JSON.stringify(contact)); } getContact() { return this.storage.get('contact').then((value) => { return value; }); } }
Hope this helps someone