最近我开始学习 Angular 2,了解 Typescript 的基本知识。因此,我尝试使用构造函数来编写代码。但我在 VS Code 编辑器中遇到类型错误,并且也无法在浏览器中获得预期的输出。我正在分享下面的代码并附上屏幕截图。如果有人告诉我如何将数组中的对象转换为 typescript 构造函数中的字符串,那将会非常有帮助?
这是代码:
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];
}
}
作者提供了从评论中复制的代码:
<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
或者,如果您想将所选英雄保留为对象,则在模板中显示名称。
app.component.html
{{myHero.name}}
对于数组,您需要循环遍历它并从数组本身在对象上显示一些有趣的内容。
<div *ngFor="#hero of heroes">
{{hero.name}}
</div>
根据您的评论,这里是显示 myHero 实例的名称和英雄数组循环的固定代码。
<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>
关于angular - 如何在 typescript 构造函数中将数组对象转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39855741/