User method error: "not a function"

I have a list of button heroes with custom animations created in button.component.ts. In the beginning they are inactive. When I click one of them, the selected one should be activated. To do this, I created a field in hero.tsunder the name stateand a function under the name toggleState()where I change the state. But when I click the button, I get an error message:

EXCEPTION: Error in http: // localhost: 3000 / app / button.component.js class ButtonComponent - built-in template: 4: 10, called: self.context. $ implicit.toggleState is not a function

I assume that I cannot create my own method similar to the one I made here. But I'm new to Angular2, so I can't say this. What have I done wrong? I played enough, "Where's Wally?" with my code and yet I cannot find anything.

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');
    }
}
+4
source share
2 answers

If you pass JSON to the TypeScript class, everything happens, so that you point to static analysis, that it can safely assume that the value belongs to this class; which does not actually change the JSON value (i.e. it does not make it an instance of this class).

, , JSON TypeScript Cast JSON TypeScript

+6

, , , - Hero.

new Hero() toggleState() Hero.

+1

Source: https://habr.com/ru/post/1659494/


All Articles