【问题标题】:Angular 5 and transition only in 'new' itemsAngular 5 和仅在“新”项目中的过渡
【发布时间】:2018-06-25 07:11:16
【问题描述】:

我的组件的模板呈现一个列表:

<div class="row">
  <div *ngFor="let m of activeModules" [@enterAnimation]>
    {{ m.name }}
  </div>
</div>

组件对其进行动画处理

@Component({
  selector: 'app-client-detail',
  templateUrl: './client-detail.component.html',
  styleUrls: ['./client-detail.component.scss'],
  animations: [

    trigger(
      'enterAnimation', [
        transition(':enter', [
          style({ opacity: 0 }),
          animate('1000ms', style({ opacity: 1}))
        ]),
        transition(':leave', [
          style({ opacity: 1 }),
          animate('1000ms', style({ opacity: 0}))
        ])
      ]
    )
  ]
})
export class ClientDetailComponent implements OnInit {
   activeModules = [{ name: 'modulo 1'}, { name: 'modulo 2'}];
}

这很好用,“div”从不透明度过渡。 如果我这样做:

ngOnInit() {
  Observable.timer(2000).subscribe(() => {
    this.activeModules =  [{ name: 'modulo 1'}, { name: 'modulo 3'}, { name: 'modulo 2'}];
}

activeModules 的数组被更新,模板再次呈现带有过渡的列表。我的问题是我只需要数组中的“新”项(在本例中为中间项)即可进行转换。有可能吗?

【问题讨论】:

    标签: javascript angular css-transitions angular-transitions


    【解决方案1】:

    当然,您只需要推送您的项目而不是再次创建您的数组。

    让我们为此创建一个函数:

    pushAt(arr, index, item) {
      arr.splice(index, 0, item); 
    }
    

    现在你可以

    ngOnInit() {
      Observable.timer(2000).subscribe(() => this.pushAt(this.activeModules, 1, { name: 'Modulo 2' }));
    }
    

    编辑也许您可以尝试使用自定义 trackby 功能:

    customTrackBy(index, item) { return index; }
    

    在你的 HTML 中

    <div *ngFor="let m of activeModules; trackBy: customTrackBy;" [@enterAnimation]>
    

    【讨论】:

    • 所以我不能使用新数组,我必须改变原来的数组?
    • 如果你想让你的动画只出现在新项目上,是的,你必须使用第一个。否则,Angular 将销毁第一个数组,然后放入第二个数组,这意味着他将撤回实际显示的元素,从而为所有元素设置动画。 (我不知道这对你是否有意义,所以如果没有,请随意说)
    • 是的,这对我来说很有意义。问题是我使用的是 redux 方法,所以我的所有数据都是不可变的。我想我必须在我的组件中做一些“技巧”来呈现这个列表,也许将原始/第一个数据存储在这个数组中,然后与来自商店的数据进行比较。
    • 您可以尝试使用我的编辑,也许这会起作用,但我不确定,因此我没有先发布它。让我及时了解这一点,以便我将其删除以避免在它不起作用时造成混淆。
    • 它与 trackBy 和 customTrack 方法一起使用。太棒了:-)
    猜你喜欢
    • 2018-10-31
    • 2018-10-05
    • 1970-01-01
    • 2015-06-19
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    相关资源
    最近更新 更多