我试图跟随Angular 2" Tour of Heroes"教程,但我遇到了问题。宣布" onSelect" (点击)事件的方法,英雄的英雄列表'空白。这就是我到目前为止所做的:
app.component.ts:
import {Component} from '@angular/core';
import {MyComponent} from './my-component';
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<h2>My Heroes</h2>
<ul class = 'heroes'>
<li *ngFor="let hero of heroes" (click)='onSelect(hero)'>
<span class='badge'>{{hero.id}}</span>
{{hero.name}}
</li>
</ul>
<h2>{{selectedHero.name}} details!</h2>
<div><label>id: </label>{{selectedHero.id}}</div>
<div>
<label>name: </label><input [(ngModel)] ='selectedHero.name' placeholder = 'name'>
</div>
`,
directives: [MyComponent]
styles: [`
.selected {
background-color: #CFD8DC !important;
color: white;
}
.heroes {
margin: 0 0 2em 0;
list-style-type: none;
padding: 0;
width: 15em;
}
.heroes li {
cursor: pointer;
position: relative;
left: 0;
background-color: #EEE;
margin: .5em;
padding: .3em 0;
height: 1.6em;
border-radius: 4px;
}
.heroes li.selected:hover {
background-color: #BBD8DC !important;
color: white;
}
.heroes li:hover {
color: #607D8B;
background-color: #DDD;
left: .1em;
}
.heroes .text {
position: relative;
top: -3px;
}
.heroes .badge {
display: inline-block;
font-size: small;
color: white;
padding: 0.8em 0.7em 0 0.7em;
background-color: #607D8B;
line-height: 1em;
position: relative;
left: -1px;
top: -4px;
height: 1.8em;
margin-right: .8em;
border-radius: 4px 0 0 4px;
}
`]
})
export class AppComponent {
title = 'Tour of Heroes';
public heroes = HEROES;
selectedHero: Hero;
function onSelect(hero: Hero) {
selectedHero: hero;
}
}
export class Hero {
id: number;
name: string;
}
const HEROES: Hero[] = [
{ id: 11, name: 'Mr. Nice' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celertitas' },
{ id: 15, name: 'Megneta' },
{ id: 16, name: 'Rubberman' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr IQ' },
{ id: 19, name: 'Magma' },
{ id: 20, name: 'Tornado' }
];
我在终端上遇到的错误:
app / app.component.ts(28,2):错误TS1005:&#39;,&#39;预期
app / app.component.ts(87,2):错误TS1068:意外的令牌。一个 期望构造函数,方法,访问器或属性。
app / app.component.ts(91,1):错误TS1128:声明或声明 预期
答案 0 :(得分:1)
我根据你得到的错误猜测是:
- 1 add comma after directives array declaration on line 28
- 2 remove 'function' before your onSelect on line 87
- 3 assign value to var selectedHero like this on line 88
selectedHero = hero;
答案 1 :(得分:1)
正如您的错误堆栈跟踪告诉您:
在directives: [MyComponent],
从function
功能声明中删除onSelect
关键字。
在hero
函数中将this.selectedHero
变量分配给selectedHero
而不只是onSelect
。
请注意,即使您执行了所有这些操作,在运行代码时您也不会看到英雄列表,因为您应该从教程中实现额外的步骤以显示列表正常。所以,解决所有这些问题,然后在你的教程中进一步发挥作用。