Angular 动画在完成时跳到不需要的值

Angular animation jumps to undesired value upon completion

我创建了一个 Angular 动画(请参阅下面的 Stackblitz link)。当包裹它的 ngIf 的条件变为真时,我想要一个元素在进入时设置动画。

动画一开始就起作用了,在width中从5px扩展到50px。 但是,一旦它到达尽头,它就会 跳跃 成为全屏宽度!

这是问题的重现: https://stackblitz.com/edit/angular-flf7ha


代码

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%'});
  }
}

TL;DR; 没有状态样式只有转换样式。

A div 默认为全角 :

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

转换结束后,div 再次采用默认值。

我建议为您的案例指定状态:

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

Here is an edit of your stackblitz.