How to convert an array object to a string in typescript constructor?

Recently I started learning Angular 2 with basic knowledge on typescript. So, I tried to work out code using constructor. But I'm getting type error in the VS Code editor and also unable to get the expected output in the browser. I am sharing the code below and attaching the screenshot too. It would be very helpful if anyone tell me how to convert the Object in the Array to a string in the typescript constructor?

Here is the code:

import { Component } from '@angular/core';

import { Hero } from './hero';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title: string;
  heroes: Array<Hero>;
  myHero: string;

  constructor() {
    this.title = "Tour Of Heroes";
    this.heroes = [
      new Hero(1, 'Windstorm'),
      new Hero(13, 'Bombasto'),
      new Hero(15, 'Magneta'),
      new Hero(20, 'Tornado')
    ];
    this.myHero = this.heroes[0];
  }
}

Screenshot: VS Code Browser


Author provided code copied from comment:

<h1>{{title}}</h1>
<h2>My favorite hero is: {{myHero}}</h2>
<p>Heroes:</p>
<ul>
  <li *ngFor="let hero of heroes"> {{ hero }} </li>
</ul>

Upvotes: 2

Views: 10198

Answers (2)

micronyks
micronyks

Reputation: 55443

You are assigning Hero class object(s) to string variable which is not compatible. So, rather than changing it to string, declare it with Hero class type. So,

myHero: string;

change it to

myHero: Hero;

And in template use it with property like,

<h1>{{title}}</h1>
   <h2>My favorite hero is: {{myHero.name}}</h2>
      <p>Heroes:</p>
         <ul>
             <li *ngFor="let hero of heroes"> {{ hero.name}} </li>
        </ul>

Upvotes: 1

Igor
Igor

Reputation: 62213

this.myHero = this.heroes[0].name; // display the name

Or if you want to keep your selected hero as an object then display the name in the template.

app.component.html

{{myHero.name}}

As for the array you need to loop over it and display something interesting on the object from the array itself.

<div *ngFor="#hero of heroes">
  {{hero.name}}
</div>

From your comment, here is your fixed code that displays the name of the myHero instance and from loop over the heros array.

<h1>{{title}}</h1>
<h2>My favorite hero is: {{myHero.name}}</h2>
<p>Heroes:</p>
<ul> <li *ngFor="let hero of heroes"> {{ hero.name }} </li> </ul>

Upvotes: 2

Related Questions