NGFOR中组件的无效动画



我有一个项目列表,我正在使用自定义组件显示它们。我希望这些物品在添加时添加并在删除它们时进行动画作用。动画似乎效果很好,但是当我尝试将它们动画出来时,它们会立即消失。我认为这是因为动画属性在组件中的元素上,但是如果我将动画属性添加到组件元素时也不起作用。

animations = [
  trigger('appear', [
    state('void', style({ height: 0, opacity: 0.2 })),
    transition('void => *', animate(200, style({ height: '*', opacity: 1 }))),
    transition('* => void', animate(200)),
  ])
];
// Custom Component
@Component({
  animations,
  selector: 'bf-post',
  template: `
  <li style="overflow: hidden" [@appear] (click)="deleteItem.emit(item.id)">
    {{item.text}}
  </li>
`,
})
export class PostComponent {
  @Input() item;
  @Output() deleteItem = new EventEmitter;
}
// Using custom component, items is an array of the posts
<ul *ngIf="items.length" [class]="wallCss">
  <bf-post *ngFor="let item of items" [item]="item"
    (deleteItem)="deleteItem($event)"></bf-post>
</ul>
  deleteItem(id) {
    const idx = this.items.findIndex(item => id === item.id);
    this.items = [
      ...this.items.slice(0, idx),
      ...this.items.slice(idx + 1),
    ];
  }

每当将项目添加到items中时,li确实会适当地进行动画。但是,当我 deleteItem删除其中一个项目时,它会立即消失。

我也尝试使用<bf-post [@appear],但这根本没有动画...动画样式可能必须在li上。 do 似乎在等待动画完成,然后才能实际删除元素。

是否有任何方法可以正确地对ngFor内部呈现的元素的空隙状态进行动画态度?

输入和离开动画会有一个错误,如果您尝试使用方法分离项目。
(在动画有机会运行之前,该组件实际上是分离的(。
有关在此处报告的错误/问题的更多信息



您需要使用主机动画绑定来查看组件离开的动画。
有关组件装饰器的主机元数据属性的更多信息


因此,您需要更改以下代码:

animations : [
  trigger('appear', [
    state('*', style({ height: 0, opacity: 0.2 })),
    transition('void => *', animate(200, style({ height: '*', opacity: 1 }))),
    transition('* => void', animate(200)),
  ])
];
// Custom Component
@Component({
  animations,
  selector: 'bf-post',
  host: { 
     '[@appear]':'true'
  }
  template: `
  <li style="overflow: hidden" (click)="deleteItem.emit(item.id)">
    {{item.text}}
  </li>
`,
})
export class PostComponent {
  @Input() item;
  @Output() deleteItem = new EventEmitter;
}
.........

省略的代码部分避免混乱

  • 请注意自定义模板中[@appear]绑定的更改,并再增加一个host元数据属性。
  • 您也可能需要将动画中的state属性更改为*而不是void 1


1 需要引用|不确定。

最新更新