I need a transition between 2 colors OnClick
. Right now, this is my code:
Typescript
animations: [
trigger('menubarState', [
state('false', style({backgroundColor:'#43a047'})),
state('true', style({backgroundColor:'#333'})),
transition('false => true', animate('1s')),
transition('true => false', animate('1s'))
])
]
...
export class MenubarComponent {
menuActive: boolean = false;
onMenuClick () {
if (this.menuActive == false) {
this.menuActive = true;
} else {
this.menuActive = false;
}
}
}
HTML
<li [@menubarState]="menuActive" (click)="onMenuClick()">
<a><span class="material-icons icon">apps</span></a>
</li>
This does change the background-color
as it should. The change, however, is instant instead of a transition.
I am using the Chrome, latest version.
BrowserAnimationsModulelinkExports BrowserModule with additional dependency-injection providers for use with animations.
The keyframes() function in Angular allows you to specify multiple interim styles within a single transition, with an optional offset to define the point in the animation where each style change should occur.
NoopAnimationsModulelinkA null player that must be imported to allow disabling of animations.
This bit me for the longest time, and what fixed it was changing my state variable from a boolean type to a string type. So - instead of tracking true
and false
, track 'true'
and 'false'
. Per Angular's docs:
An animation state is a string value that you define in your application code.
Change your MenubarComponent class to this:
export class MenubarComponent {
menuActive: string = 'false';
onMenuClick () {
if (this.menuActive === 'false') {
this.menuActive = 'true';
} else {
this.menuActive = 'false';
}
}
}
I think it's dumb. Booleans are obviously good options for binary states.
More info: https://angular.io/guide/animations#states-and-transitions
Expanding on the answer that Aaron Krauss provided. It is having issues with the direct interpretation of the true / false values; however, if you would rather not reference a string context, you can replace true and false in the above with the numbers 1 (true) and 0 (false). This proved to fix my issue and didn't require any annoying string interpretations.
trigger('menubarState', [
state('0', style({backgroundColor:'#43a047'})),
state('1', style({backgroundColor:'#333'})),
transition('0 => 1', animate('1s')),
transition('1 => 0', animate('1s'))
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With