Using Angular, I'm trying to pass a local variable from constructor the into the HTML.
Here is my TS:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
@Component({
selector: 'page-random',
templateUrl: 'random.html'
})
export class RandomPage {
constructor(public navCtrl: NavController) {
var restaurants = [
'Restaurant1',
'Restaurant2',
'Restaurant3'
];
var restaurant = restaurants[Math.floor(Math.random()*restaurants.length)];
console.log(restaurant);
}
}
Here is my HTML:
<ion-content padding>
<ion-item>
{{restaurant}}
</ion-item>
</ion-content>
restaurant
is being logged when the constructor fires. I'm just not sure how to display it in the HTML. What am I missing?
You can declare variables in html code by using a template element in Angular 2 or ng-template in Angular 4+. Templates have a context object whose properties can be assigned to variables using let binding syntax. Note that you must specify an outlet for the template, but it can be a reference to itself.
Variable specifying a namelink If the variable specifies a name on the right-hand side, such as #var="ngModel" , the variable refers to the directive or component on the element with a matching exportAs name.
To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .
You can't bind var
variable to the html (because it's not a property!). Create a string variable and bind that into the html. The this
keyword is used to access the property inside the component.
export class RandomPage {
restaurant: string;
constructor(public navCtrl: NavController) {
var restaurants = [
'Restaurant1',
'Restaurant2',
'Restaurant3'
];
this.restaurant = restaurants[Math.floor(Math.random()*restaurants.length)];
console.log(this.restaurant);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With