CSS 过渡 Angular 2+ ngClass

CSS transitions with Angular 2+ ngClass

我有一个非常简单的 CSS class 可以通过基本的缓和过渡切换 <tr> 元素的不透明度:

 tbody tr {
   transition: opacity 1s ease;
 }

 tbody.blur tr {
   opacity: .3;
 }

 tbody.blur tr.focus {
   opacity: 1;
 }

[ngClass] 设置和删除 .blur.focus classes。 (重点是模糊除聚焦行之外的所有行。)不透明度按预期工作,但过渡没有。如果我使用开发工具将 classes 直接输入到 tbodytr 标签中,不透明度会发生变化,但如果 classes 由 ngClass 设置, 没有过渡。

我尝试设置 encapsulation: ViewEncapsulation.None,但没有任何效果。

我是否遗漏了过渡和 ngClass 的内容?

编辑:ngClass代码基本上是

<tbody [ngClass]="{blur: focused > -1}">
  <tr [ngClass]="{focus: focused === item.id}" *ngFor="let item of items">

组件 class 有一个 focused 变量,在模糊时设置为 -1,在 focus 时设置为相应的 id。

编辑 - 解决方案

一个计算 getter 连续 returns 一个新的 Array 实例阻止 CSS 转换;示例 here. If you return the same array instance, the transition occurs. The getter should return the same, mutable property of the class instance like this。请注意,后一个示例中的 属性 是由其他 getter 组成的,这很好。

一个getter喜欢

  get tableData() {
    return [
        {id: 1, name: 'One', data: this.one},
        {id: 2, name: 'Two', data: this.two},
        {id: 3, name: 'Three', data: this.three},
        {id: 4, name: 'Four', data: this.four},
        {id: 5, name: 'Five', data: this.five},
        {id: 6, name: 'Six', data: this.six}
    ];
  }

returns 每次调用 tableData 时一个新的数组实例。 Angular 每次更改检测运行时都会调用 getter 并检测到更改,因为它获得了不同的实例。这会导致严重的性能问题并破坏动画,因为如果不断重新创建项目,动画将无法工作。

更好的方法是

class MyComponent {  
  data = [
    {id: 1, name: 'One', data: this.one},
    {id: 2, name: 'Two', data: this.two},
    {id: 3, name: 'Three', data: this.three},
    {id: 4, name: 'Four', data: this.four},
    {id: 5, name: 'Five', data: this.five},
    {id: 6, name: 'Six', data: this.six}
  ];

  get tableData() {
    return this.data;
  }
}

这样 Angular 更改检测每次调用 tableData 时都会获得相同的实例,并且 Angular 会很高兴。 如果某些事件导致内容或整个数组发生变化,这当然很好,但它不应该仅仅因为 Angular 随后检查两次而改变。