0

I've created an Angular animation (please see Stackblitz link below). I want an element to animate on entry, when the condition of the ngIf that wraps it becomes true.

The animation works at the beginning, expanding from 5px to 50px in width. But then, once it reaches the end, it just jumps to become full screen width!

Here is a reproduction of the issue: https://stackblitz.com/edit/angular-flf7ha


The code

app.component.html

<button (click)="addBars()">Toggle Bar</button>

<div *ngFor="let bar of bars">
  <div id="bar" @horizontalBarGrow [style.width.%]="bar.width"></div>
</div>

app.component.ts

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  animations: [
    trigger('horizontalBarGrow', [
        transition(':enter', [
            style({ width: '5px' }),
            animate('500ms ease-out', style({ width: '50px' })),
        ]),
    ])
  ]
})
export class AppComponent  {
  name = 'Angular';

  bars = []

  addBars() {
    this.bars.push({ width: '10%'});
    this.bars.push({ width: '40%'});
  }
}
CodyBugstein
  • 21,984
  • 61
  • 207
  • 363

1 Answers1

0

TL;DR; There is no states style only transitions style.

A div by default is full width :

A div with the default width :
<div style="background-color: #3498db; height: 50px;"></div>

Once the transition ends, the div takes the defaults values again.

I suggest specifying states for your case :

trigger('horizontalBarGrow', [
  state('true', style({ width: '50px' })),
  state('false', style({ width: '0px' })),
  transition('false <=> true', animate(500))
])

Here is an edit of your stackblitz.

ibenjelloun
  • 7,425
  • 2
  • 29
  • 53
  • Thanks for your answer. However it is important that I use the `:enter` and `:leave` transitions because I want this code to work inside an `ngFor`. That is, I can't have separate `showBar` variables for 20 "bars" in an array of bars – CodyBugstein Dec 13 '18 at 15:33
  • You want all the progressbars to show the exact same animation at the same time ? – ibenjelloun Dec 13 '18 at 15:54
  • Yes. The are actually not progress bars in this case, but part of a horizontal bar chart. See the update I've made in the StackBlitz https://stackblitz.com/edit/angular-flf7ha – CodyBugstein Dec 13 '18 at 16:15
  • 1
    You can define params in your animation and then pass them to the animation, here is a running example with this solution : https://stackblitz.com/edit/stackoverflow-53714352-3 . Another solution would be to encapsulate the div inside another div with the desired size, here is a running example with the second solultion : https://stackblitz.com/edit/stackoverflow-53714352-2 – ibenjelloun Dec 14 '18 at 08:04