为 *ngFor 中的元素应用不同的动画

Apply different animations for elements in *ngFor

所以我正在尝试为 *ngFor 循环中的元素应用不同的动画。最简单的示例如下:

@Component({
  selector: 'app-anims',
  templateUrl: './anims.component.html',
  styleUrls: ['./anims.component.css'],
  animations: [
    trigger('scrolledToAnimation0', [
      state('first', style({
        backgroundColor: "white"
      })),
      state('second', style({
        backgroundColor: "yellow"
      })),
      transition('first => second', [
        animate('1s')
      ]),
    ]),
    trigger('scrolledToAnimation1', [
      state('first', style({
        backgroundColor: "white"
      })),
      state('second', style({
        backgroundColor: "green"
      })),
      transition('first => second', [
        animate('0.40s')
      ]),
    ])
  ]
})

scrolledTo: boolean = false;
divElements: string[] = ["foo", "bar"];

  @HostListener('window:scroll', ['$event'])
    checkScroll() {
      let componentPosition = this.el.nativeElement.offsetTop0;
      let scrollPosition = window.pageYOffset;

      if (scrollPosition >= componentPosition && this.scrolledTo === false) {
        this.scrolledTo = true;
      }

    }

HTML:

<div *ngFor="div of divElements; let i = index" [@scrolledToAnimation0]="???" [@scrolledtoAnimation1]="???"></div>

我尝试了几种方法,其中 none 似乎有效。感谢任何帮助 - 提前致谢。

顺便想通了。变量 "index"(或此处的别名 "i")可在其声明的同一 div 中访问,并且可用于引用每个 *ngFor 元素。

通过以下方式完成:

<div
*ngFor="let item of Array; let i = index;"
[@animationName]="i === 0 ? 'firstAnimation' : 'secondAnimation'">
</div>

上面引用了数组的第一个元素。