I am working on a project where I have a collection of hero buttons that come with a customized animation which is defined in the button.component.ts
file. These buttons start off as inactive, but when one is clicked, it should become active. To achieve this functionality, I added a field called state
in the hero.ts
file and implemented a method called toggleState()
to update the state. However, upon clicking the button, I encountered the following error:
EXCEPTION: Error in http://localhost:3000/app/button.component.js class ButtonComponent - inline template:4:10 caused by: self.context.$implicit.toggleState is not a function
It seems like my approach for creating a custom method may not be correct. As a beginner in Angular2, I'm having difficulty pinpointing the issue. I've spent a significant amount of time reviewing my code, yet I haven't been able to identify the problem.
Here is a snippet from the button.component.ts
file:
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);
}
}
This is how the hero.ts
file looks:
export class Hero {
id: number;
name: string;
state: string;
constructor() {
this.state = 'inactive';
}
public toggleState(): void{
this.state = (this.state === 'active' ? 'inactive' : 'active');
}
}