【问题标题】:CSS transitions with Angular 2+ ngClassAngular 2+ ngClass 的 CSS 过渡
【发布时间】:2018-07-13 23:30:02
【问题描述】:

我有一个非常简单的 CSS 类,它可以通过基本的轻松过渡来切换 <tr> 元素的不透明度:

 tbody tr {
   transition: opacity 1s ease;
 }

 tbody.blur tr {
   opacity: .3;
 }

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

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

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

我是否缺少转换和ngClass 的内容?

编辑:ngClass 代码基本上是

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

组件类有一个焦点变量,在模糊时设置为 -1,在焦点时设置为相应的 id。

编辑 - 解决方案

不断返回新 Array 实例的计算 getter 会阻止 CSS 转换;例如here。如果返回相同的数组实例,transition occurs。 getter 应该返回类实例的相同的可变属性,例如this。请注意,后一个示例中的属性由其他 getter 组成,这很好。

【问题讨论】:

  • 请添加代码。您在哪里添加了 CSS?
  • 请粘贴ngClass代码!
  • @GünterZöchbauer 谢谢,CSS 已添加到 CLI 创建的 component.css 文件中。
  • 如果类名是固定的,你应该更喜欢[class.blur]="focused &gt; -1"(和[class.focus]="focused === item.id"
  • @GünterZöchbauer 不错的提示;谢谢。

标签: css angular css-transitions getter


【解决方案1】:

像这样的吸气剂

  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}
    ];
  }

每次调用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 随后检查两次而改变。

【讨论】:

    猜你喜欢
    • 2016-07-24
    • 2017-02-19
    • 2018-10-18
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多