I have an Angular 4 component with a list of items. I followed the Angular documentation (https://angular.io/api/animations/animation) on setting up Enter and Leave animation when item is added or removed. But the same animation is played on all existing items in the list when the view is loaded. Is there a way to turn off animation on the initial view load but re-enable it after view is loaded?
2 Answers
Just in case someone is looking for actual answer - if you have animation with :enter trigger, it can be done with @.disabled attribute like so:
<div @someAnimation [@.disabled]="animationDisabled"></div>
And then in component you just need to change the animationDisabled property to true after view is initialized:
@Component({
// ...
})
export class SomeComponent implements AfterViewInit {
animationDisabled: boolean = true;
ngAfterViewInit(): void {
this.animationDisabled = false;
}
}
Now animation won't run on component init but will still work during component's lifetime
3 Comments
Bob der Baumeister
This is working, but it causes "Expression has changed after it was checked" while on
ng test.ThaFog
@BobderBaumeister then try to run it as a microtask:
queueMicrotask(() => { this.animationDisabled = false; });Gustavo López Frutos
@BobderBaumeister You can just change the value OnInit with setTimeOut: @Component({ // ... }) export class SomeComponent implements OnInit { animationDisabled: boolean = true; ngOnInit(): void { setTimeout(()=> this.animationDisabled = false); } }
You can define a dedicated animation state for added components.
Then you will have 3 transitions
void => *// Initial load - no animationsvoid => added// Animation for added components* => void// Animation for removal of component
2 Comments
Lazar Ljubenović
Is "added" a special state automatically recognized by Angular or do I need to do something to add "added"?
Alexander Trakhimenok
You would need to define CSS representation for the "added" state and then trigger the state.