Using .ts file variables in .html file


#1

Hi,

I have a jsonp data source and the response looks like below:

My controller (microsite.ts) look like this:

import { Component } from ‘@angular/core’;
import { NavController } from ‘ionic-angular’;
import { Http, Jsonp } from ‘@angular/http’;

@Component({
selector: ‘page-microsite’,
templateUrl: ‘microsite.html’
})
export class MicrositePage {

public micdetails: any;

constructor(public navCtrl: NavController, private http: Http, public jsonp: Jsonp) {

this.jsonp.get("http://localhost/way2college/index.php?option=com_directory&task=app.getmicrositedetails&id=125")
.subscribe(
	res => {
    this.micdetails = res.json();
    console.log(this.micdetails);
	}
);

}

}

When I try to console.log the variable this.micdetails.college_details.name it works well, but when I try to use the same variable in template file (microsite.html) like:

Microsite {{micdetails.college_details.name}}

I get error as:

I am unable to understand, how can I use controller variables in template file.


#2

That’s because of asynchronicity. As you can see in your log the error occurs before the object get’s logged. Which means you’re binding in your html to something that doesn’t exist when rendering the component (i.e. {{micdetails.college_details.name}}) . Make sure micdetails is loaded before rendering the HTML or initialize micdetails with empty settings in your class.

Easiest solution is to *ngIf="!!micdetails" on the top of the specific micdetails item. This makes sure micdetails isn’t empty so Angular won’t try and render it when it isn’t available yet.