如何使用Angular的ngFor实现项目重新排序/随机播放动画?

Wen*_*ris 6 javascript animation angular

Vue用户很容易实现这样的项目随机播放动画,请参阅他们的官方文档:

随机动画

我搜索了很多,但找不到Angular用户的解决方案.ngFor在洗牌时似乎切换项目内容而不是移动项目.

这是我的演示:http://embed.plnkr.co/3IcKcC/

单击shift时,您应该看到项目移动动画,这要归功于li {transform: all 1s;}.但是当你洗牌时,没有动画.所以我在这里要求一个解决方案.

yur*_*zui 14

这里是简单实现这样的功能Plunker Example

1)构建指令

@Directive({
  selector: '[transition-group-item]'
})
export class TransitionGroupItemDirective {
  prevPos: any;

  newPos: any;

  el: HTMLElement;

  moved: boolean;

  moveCallback: any;

  constructor(elRef: ElementRef) {
    this.el = elRef.nativeElement;
  }
}


@Component({
  selector: '[transition-group]',
  template: '<ng-content></ng-content>'
})
export class TransitionGroupComponent {
  @Input('transition-group') class;

  @ContentChildren(TransitionGroupItemDirective) items: QueryList<TransitionGroupItemDirective>;

  ngAfterContentInit() {
    this.refreshPosition('prevPos');
    this.items.changes.subscribe(items => {
      items.forEach(item => {
        item.prevPos = item.newPos || item.prevPos;
      });

      items.forEach(this.runCallback);
      this.refreshPosition('newPos');
      items.forEach(this.applyTranslation);

      // force reflow to put everything in position
      const offSet = document.body.offsetHeight;
      this.items.forEach(this.runTransition.bind(this));
    })
  }

  runCallback(item: TransitionGroupItemDirective) {
    if(item.moveCallback) {
      item.moveCallback();
    }
  }

  runTransition(item: TransitionGroupItemDirective) {
    if (!item.moved) {
      return;
    }
    const cssClass = this.class + '-move';
    let el = item.el;
    let style: any = el.style;
    el.classList.add(cssClass);
    style.transform = style.WebkitTransform = style.transitionDuration = '';
    el.addEventListener('transitionend', item.moveCallback = (e: any) => {
      if (!e || /transform$/.test(e.propertyName)) {
        el.removeEventListener('transitionend', item.moveCallback);
        item.moveCallback = null;
        el.classList.remove(cssClass);
      }
    });
  }

  refreshPosition(prop: string) {
    this.items.forEach(item => {
      item[prop] = item.el.getBoundingClientRect();
    });
  }

  applyTranslation(item: TransitionGroupItemDirective) {
    item.moved = false;
    const dx = item.prevPos.left - item.newPos.left;
    const dy = item.prevPos.top - item.newPos.top;
    if (dx || dy) {
      item.moved = true;
      let style: any = item.el.style;
      style.transform = style.WebkitTransform = 'translate(' + dx + 'px,' + dy + 'px)';
      style.transitionDuration = '0s';
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

2)使用如下

<ul [transition-group]="'flip-list'">
  <li *ngFor="let item of items" transition-group-item>
    {{ item }}
  </li>
</ul>
Run Code Online (Sandbox Code Playgroud)


paw*_*wel 7

这是我的@yurzui 代码版本。变化:

  • 支持项目的插入和删除
  • 强制回流在 webpack 优化中幸存下来


import { Component, ContentChildren, Directive, ElementRef, Input, QueryList } from '@angular/core';

@Directive({
    selector: '[transition-group-item]'
})
export class TransitionGroupItemDirective {
    prevPos: any;
    newPos: any;
    el: HTMLElement;
    moved: boolean;
    moveCallback: any;

    constructor(elRef: ElementRef) {
        this.el = elRef.nativeElement;
    }
}


@Component({
    selector: '[transition-group]',
    template: '<ng-content></ng-content>'
})
export class TransitionGroupComponent {
    @Input('transition-group') class;

    @ContentChildren(TransitionGroupItemDirective) items: QueryList<TransitionGroupItemDirective>;

    ngAfterViewInit() {
        setTimeout(() => this.refreshPosition('prevPos'), 0); // save init positions on next 'tick'

        this.items.changes.subscribe(items => {
            items.forEach(item => item.prevPos = item.newPos || item.prevPos);
            items.forEach(this.runCallback);
            this.refreshPosition('newPos');
            items.forEach(item => item.prevPos = item.prevPos || item.newPos); // for new items

            const animate = () => {
                items.forEach(this.applyTranslation);
                this['_forceReflow'] = document.body.offsetHeight; // force reflow to put everything in position
                this.items.forEach(this.runTransition.bind(this));
            }

            const willMoveSome = items.some((item) => {
                const dx = item.prevPos.left - item.newPos.left;
                const dy = item.prevPos.top - item.newPos.top;
                return dx || dy;
            });

            if (willMoveSome) {
                animate();
            } else {
                setTimeout(() => { // for removed items
                    this.refreshPosition('newPos');
                    animate();
                }, 0);
            }
        })
    }

    runCallback(item: TransitionGroupItemDirective) {
        if (item.moveCallback) {
            item.moveCallback();
        }
    }

    runTransition(item: TransitionGroupItemDirective) {
        if (!item.moved) {
            return;
        }
        const cssClass = this.class + '-move';
        let el = item.el;
        let style: any = el.style;
        el.classList.add(cssClass);
        style.transform = style.WebkitTransform = style.transitionDuration = '';
        el.addEventListener('transitionend', item.moveCallback = (e: any) => {
            if (!e || /transform$/.test(e.propertyName)) {
                el.removeEventListener('transitionend', item.moveCallback);
                item.moveCallback = null;
                el.classList.remove(cssClass);
            }
        });
    }

    refreshPosition(prop: string) {
        this.items.forEach(item => {
            item[prop] = item.el.getBoundingClientRect();
        });
    }

    applyTranslation(item: TransitionGroupItemDirective) {
        item.moved = false;
        const dx = item.prevPos.left - item.newPos.left;
        const dy = item.prevPos.top - item.newPos.top;
        if (dx || dy) {
            item.moved = true;
            let style: any = item.el.style;
            style.transform = style.WebkitTransform = 'translate(' + dx + 'px,' + dy + 'px)';
            style.transitionDuration = '0s';
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

更正确(并且符合 TSLint)是使用不同的指令名称,如:

@Directive({
    selector: '[appTransitionGroupItem]'
})
Run Code Online (Sandbox Code Playgroud)

并使用组件作为元素而不是重载输入名称:

@Component({
    selector: 'app-transition-group',
    template: '<ng-content></ng-content>'
})
export class TransitionGroupComponent implements AfterViewInit {
    @Input() className;
Run Code Online (Sandbox Code Playgroud)

这为代码提供了更好的 Angular 结构,我的合规、更好的阅读 (YMMV) 代码是:

<app-transition-group [className]="'flip-list'">
  <div class="list-items" *ngFor="let item of items" appTransitionGroupItem>
  etc
Run Code Online (Sandbox Code Playgroud)

另外,如果您想知道为什么过渡动画不起作用,请不要忘记所需的 CSS:

.flip-list-move {
  transition: transform 1s;
}
Run Code Online (Sandbox Code Playgroud)