【问题标题】:Apply different animations for elements in *ngFor为 *ngFor 中的元素应用不同的动画
【发布时间】:2018-11-11 10:43:52
【问题描述】:

所以我尝试为 *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>

我尝试了几种方法,但似乎都不起作用。任何帮助表示赞赏 - 在此先感谢。

【问题讨论】:

    标签: angular angular-animations


    【解决方案1】:

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

    通过以下方式完成:

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

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

    【讨论】:

      猜你喜欢
      • 2017-07-11
      • 2020-11-05
      • 2017-08-15
      • 2013-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-13
      • 2014-02-02
      相关资源
      最近更新 更多