Ionic2 two-way binding Problem with import class


#1

Hi everyone i have this problem for a couple of hours now and i dont know what is happening. (im pretty new to Ionic2) so here it is:

I have a adding.ts :

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Transaction } from '../../database';

@Component({
  selector: 'page-adding',
  templateUrl: 'adding.html'
})
export class AddingPage {

  model : Transaction;

  constructor(public navCtrl: NavController) {
  }

  ionViewDidLoad() {
  	this.model = new Transaction(null, "");
  }

  save(){
  	this.model.save();
  }

}

There, you can see model : Transaction that is a class im importing from another .ts file and have this structure:

export class Transaction implements ITransaction{
	id?: number;
	amount: number;
	lat: number;
	lng: number;
	title: string;
	imageUrl: string;

	constructor(amount:number, title:string, lat?:number, lng?:number, id?:number, imageUrl?:string){
		this.amount = amount;
		this.title = title;
		if(lat) this.lat = lat;
		if(lng) this.lng = lng;
		if(imageUrl) this.imageUrl = imageUrl;
		if(id) this.id = id;
	}
}

but when i try to use ngModel in my adding.html i keep getting Cannot read property ‘title’ of undefined

here is my adding.html:

<ion-header>

  <ion-navbar>
    <ion-title>Agregar Movimiento</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding>
<ion-item>
	<ion-label floating>Descripción</ion-label>
	<ion-input type="text" [(ngModel)]="model.title" name="title"></ion-input>
</ion-item>
<ion-item>
	<ion-label floating>Monto</ion-label>
	<ion-input type="number" name="amount"></ion-input>
</ion-item>
<div class="actions">
	<button ion-button>Agregar</button>
</div>
</ion-content>

Please help me out :smiley:


#2

You are initializing model after the template tries to access it. You have two options: either initialize model earlier (such as in the constructor) or bulletproof the template with conditional operators so that it can handle the case where model is not yet defined.


#3

that makes a lot of sense. in terms of best practices what do you think should be the right way ? as of now im initializing it in the constructor.
Thanks for your anwser man :smile: