Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Angular, how can I output a variable to HTML?

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?

like image 939
cfoster5 Avatar asked Dec 31 '17 04:12

cfoster5


People also ask

How do you declare a variable in HTML Angular?

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.

What is VAR in Angular?

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.

How do I pass a template reference variable in component?

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 .


1 Answers

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);
like image 101
Sachila Ranawaka Avatar answered Oct 13 '22 03:10

Sachila Ranawaka