轮播动画不能 运行 正确处理真实数据

Carousel animation not running properly with real data

参考这个 ,我实现了动画,但那是用虚拟数据。

现在,当真正的数据出现时(大约需要一秒钟),动画无法正常工作,这是因为动画功能在数据出现之前执行:

ngOnInit() {
    this.getData();
}

  ngAfterViewInit() {
    this.calculateDimensions();
    this.animateCarousel();     // Animation Function
  }

  getData() {
    timer(1000).subscribe(res => {
      this.data = [
        {
          name: "Max",
          age: 27
        },
        ...
        ...
      ]
     });
  }

我试过在数据来了之后执行动画功能,还是不行。

getData() {
    timer(1000).subscribe(res => { ...
    });
    this.calculateDimensions();
    this.animateCarousel();
}

Stackbliz link.

谢谢。

首先要做的是 - 您发布的代码将不会在提供数据后执行这些操作。为此,他们需要在内部订阅中,即在分配 this.data 的同一范围内。

尽管如此,即使这些方法在 this.data 赋值之后 运行,它仍然会产生错误。

请注意,您的 items 查询 ID 为 card 的项目。这些项目基于您的 data 属性 使用 ngFor。但是 DOM 元素不会立即生成,所以起初您的 QueryList 将是空的,即使在 this.data 被分配之后也是如此。

幸运的是,QueryList 有一个 changes 属性,它会在每次内容更改时发出。这意味着您可以订阅它并在进行更改后开始动画,例如

ngAfterViewInit() {
    this.items.changes.subscribe(x => {
      this.calculateDimensions();
      this.animateCarousel();
    });
  }

这样,每次更改 data 的内容时,这些方法都会 运行。还没有深入研究您的代码 - 您可能只想 运行 在第一次更改后查看它们,然后您可以这样做:

this.items.changes
  .pipe(take(1))
  .subscribe(x => {
    this.calculateDimensions();
    this.animateCarousel();
  });

因此,我只需将 2 个方法包装在 setTimeout 函数中 100 毫秒,就可以让它与您上次的尝试一起工作...

但是,更好的解决方案是监听 dom 变化并检测何时加载#card div...

https://nitayneeman.com/posts/listening-to-dom-changes-using-mutationobserver-in-angular/