6

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?

4
  • can you mention the angular version? or is this angular 1? Commented Dec 31, 2017 at 4:13
  • @NevilleNazerane This is Angular 5. Commented Dec 31, 2017 at 4:15
  • i would recommend adding it as a tag Commented Dec 31, 2017 at 4:16
  • does this.restaurant = ... instead of var restaurant work? you want the value to be a property of the controller, not just a random variable... Commented Dec 31, 2017 at 4:19

2 Answers 2

6

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Minor edits: variables != properties/fields/members.
5

restaurant is defined in the constructor scope, not as an instance variable. As such, Angular has no access to the variable. You need to modify your code to match this general format that defines a public instance variable bar, and then assigns a value to it inside of its the Foo class constructor.

export class Foo() {
     public bar: string;

     constructor() {
         this.bar = 'a string';
     }
}

Here's the TypeScript handbook section on variable declarations. It might be worth a read.

1 Comment

Note that, according to the TypeScript documentation linked, variables are not members! Here is the TypeScript overview of classes: members = properties + methods (+ constructor), but not variables (as defined with var or let or parameters).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.