Kumar Kumar - 3 months ago 12
TypeScript Question

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';

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];

VS Code

Author provided code copied from comment:

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

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.



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">

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

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