【问题标题】:Angular2 *ngFor animation of pushed away elementsAngular2 *ngFor 推开元素的动画
【发布时间】:2017-07-11 14:07:18
【问题描述】:

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

有没有办法让其他元素很好地移动,就像附图中描述的那样?

【问题讨论】:

    标签: javascript angular animation ngfor


    【解决方案1】:

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

    Plunker Example

    @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

    【讨论】:

    • 您的回答几乎就是我所需要的,它绝对帮助我找到了我认为完美的解决方案。我一直缺少的关键是,我不知道 height: '*' 是一回事。我在移除元素并将序列更改为组时添加了边距-底部过渡以消除跳动的动画(也许它似乎在 gif 上排序,我希望动画是平行的,但持续时间不同)。非常感谢,这是我的Plunker
    • 这里是关于height: "*"angular.io/docs/ts/latest/guide/…的文档
    • 文档的最新链接 (opacity: '*'):angular.io/guide/…
    猜你喜欢
    • 2016-11-05
    • 2017-08-16
    • 2017-02-03
    • 2017-08-15
    • 1970-01-01
    • 2017-06-02
    • 2016-07-15
    • 2017-07-19
    • 1970-01-01
    相关资源
    最近更新 更多