【发布时间】:2018-04-05 20:43:10
【问题描述】:
我有一个英雄按钮列表,其中包含在button.component.ts 中创建的自定义动画。一开始,它们是不活动的。当我按下其中之一时,选定的应该会变为活动状态。为此,我在hero.ts 中创建了一个名为state 的字段和一个名为toggleState() 的函数,我在其中更改了状态。但是当我按下按钮时,我收到错误:
例外:http://localhost:3000/app/button.component.js 类 ButtonComponent 中的错误 - 内联模板:4:10 由以下原因引起:self.context.$implicit.toggleState 不是函数
我的猜测是我无法像这里那样创建自定义方法。但我是 Angular2 的新手,所以我不能说清楚。我做错了什么?我玩够了“沃利在哪里?”使用我的代码,但我仍然找不到任何东西。
button.component.ts:
import { Component, Input, OnInit, trigger, state, style, transition, animate
} from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
moduleId: module.id,
selector: 'button-collection',
template: `
<button *ngFor="let hero of heroes"
[@heroState]="hero.state"
(click)="hero.toggleState()">
{{hero.name}}
</button>
`,
styleUrls: ['heroes.component.css'],
animations: [
trigger('heroState', [
state('inactive', style({
backgroundColor: '#e1e1e1',
transform: 'scale(1)'
})),
state('active', style({
backgroundColor: '#dd1600',
transform: 'scale(1.1)'
})),
transition('inactive => active', animate('100ms ease-in')),
transition('active => inactive', animate('100ms ease-out'))
])
],
})
export class ButtonComponent implements OnInit {
heroes: Hero[];
constructor(private heroService: HeroService) {
}
ngOnInit(): void {
this.heroService.getHeroes()
.then(heroes => this.heroes = heroes);
}
}
hero.ts:
export class Hero {
id: number;
name: string;
state: string;
constructor() {
this.state = 'inactive';
}
public toggleState(): void{
this.state = (this.state === 'active' ? 'inactive' : 'active');
}
}
【问题讨论】:
-
我认为您遗漏了太多代码。
class Hero是什么?一个组件,一个服务,还是别的什么?什么是“等等”?它是否包含hero引用? -
@GünterZöchbauer:简短说明:
hero.ts类是我用于英雄列表的模型(即 Hero[])。//and so on包含字段heroes和获取英雄列表的方法。我会为你添加它。 -
您不会在
getHeroes()中将JSON 转换为Hero? -
@GünterZöchbauer 就是这样。我向服务器发出 HTTP 请求以接收英雄,然后将其从 JSON 转换为
Hero[]。 -
@SovietPanda 那么你就有答案了。 JSON unmarshaller 不知道您的类,并创建包含来自 JSON 的字段的对象。但是这些对象不是你的 Hero 类的实例。他们没有任何方法。您需要遍历 JSON 并将每个对象转换为 Hero。或者你需要把这个 toggle() 功能放到你的组件中,并让它接受一个 Hero 作为参数。归功于 Gunter,所以我不会将此作为答案发布。
标签: angular typescript