自定义创建的方法错误:“不是函数”

2023-11-22

我有一个英雄按钮列表,其中创建了自定义动画button.component.ts。一开始,他们是不活跃的。当我按下其中之一时,所选的应该变为活动状态。为此,我创建了一个字段hero.ts called state和一个名为的函数toggleState()我在哪里改变状态。但是当我按下按钮时,我收到错误:

例外:错误http://localhost:3000/app/button.component.jsclass ButtonComponent - 内联模板:4:10 导致: self.context.$implicit.toggleState 不是函数

我的猜测是我无法像这里那样创建自定义方法。但我是 Angular2 的新手,所以我不能真正告诉它。我做错了什么?我已经玩够了“沃利在哪里?”用我的代码,我仍然找不到任何东西。

按钮.组件.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');
    }
}

如果您将 JSON 转换为 TypeScript 类,那么所发生的一切就是您向静态分析表明它可以安全地假设该值属于该类;这实际上根本不会改变 JSON 值(即它不会使其成为该类的实例)。

你想要的可能是如何将 JSON 对象转换为 Typescript 类 or 将 JSON 对象转换为 TypeScript 类实例

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

自定义创建的方法错误:“不是函数” 的相关文章