We have a very simple component that should be faded in and out on :enter
and :leave
events:
import { Component, HostBinding } from '@angular/core';
import { animate, style, transition, trigger } from '@angular/animations';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss'],
animations: [
trigger('host', [
transition(':enter', [
style({ opacity: 0 }),
animate('240ms linear', style({ opacity: 1 })),
]),
transition(':leave', [
style({ opacity: 1 }),
animate('240ms linear', style({ opacity: 0 })),
])
]),
]
})
export class TestComponent {
@HostBinding('@host') host() {
return true;
}
}
The component is used like this:
<app-test *ngIf="someBoolean"></app-test>
Now the animation on :enter
does run. But the element is not faded out, when the component is being removed (the variable someBoolean
becomes false
).
What is missing?
Using
*ngIf
in the parent component makes the element animations not to be registeredLets follow what happens
someBoolean
=> starting withfalse
<app-test *ngIf='someBoolean'></app-test>
does not existsomeBoolean
=>true
<app-test></app-test>
app-test
then loaded the animations! But at what point is animations to be triggered? The answer to this question is why your animations are not being triggered. We need to reqister the animations before they can be appliedSo Lets stop the above sequence of events and retry the steps
someBoolean
=> starting withfalse
<app-test [shown]='someBoolean'></app-test>
createdsomeBoolean
=>true
<app-test></app-test>
Okay, now that we have an idea of how this would work lets get down to code
Component usage
Component TS File
I have commented out
@HostBinding
as I didn't see how it is implemented here.Finally we can apply
*ngIf
in the contents of the componentSee Demo Here