Angular2 * ng用于推开元素的动画

时间:2017-02-21 19:14:26

标签: javascript angular animation ngfor

我已经看过很多关于进入或离开元素的动画教程(下面图片中的“新元素”),但被推开的其他元素(元素1和2)通常只是传送到他们的新位置

enter image description here

有没有办法让其他元素动画很好地移动,如附图所示?

1 个答案:

答案 0 :(得分:20)

您可以使用angular2 animation API来实现它。

<强> Plunker Example

enter image description here

@Component({
  selector: 'my-app',
  template: `
     <div class="container">
      <div *ngFor="let item of items; let i = index" class="item"  (click)="remove(i)"
        [@anim]="item.state">
        {{ item.name }}
      </div>
    </div>
    <div class="aside">
      <button (click)="push()">Push</button>
    </div>
  `,
  animations: [
     trigger('anim', [
        transition('* => void', [
          style({ height: '*', opacity: '1', transform: 'translateX(0)', 'box-shadow': '0 1px 4px 0 rgba(0, 0, 0, 0.3)'}),
          sequence([
            animate(".25s ease", style({ height: '*', opacity: '.2', transform: 'translateX(20px)', 'box-shadow': 'none'  })),
            animate(".1s ease", style({ height: '0', opacity: 0, transform: 'translateX(20px)', 'box-shadow': 'none'  }))
          ])
        ]),
        transition('void => active', [
          style({ height: '0', opacity: '0', transform: 'translateX(20px)', 'box-shadow': 'none' }),
          sequence([
            animate(".1s ease", style({ height: '*', opacity: '.2', transform: 'translateX(20px)', 'box-shadow': 'none'  })),
            animate(".35s ease", style({ height: '*', opacity: 1, transform: 'translateX(0)', 'box-shadow': '0 1px 4px 0 rgba(0, 0, 0, 0.3)'  }))
          ])
        ])
    ])
  ]
})
export class AppComponent {
  items: any[] = [
    { name: 'Element 1' },
    { name: 'Element 2' }
  ];

  push() {
    this.items.splice(1, 0, { name: 'New element', state: 'active' });
  }

  remove(index) {
     this.items.splice(index, 1);
  }
}

不要忘记导入BrowserAnimationsModule