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

advertisements

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>


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>