【问题标题】:NGStyle Changes Not Always ReflectedNGStyle 更改并不总是反映
【发布时间】:2021-01-10 23:50:36
【问题描述】:

我有一个采用 ng 样式的元素,但是当样式对象更改时,样式并不总是按预期应用。我专门指的是下面的 css animation,但我已经看到 background 的类似行为。

<div [ngStyle]="_innerStyle">
export class WidgetContainerComponent implements OnInit {
  _innerStyle?: {
    [klass: string]: any;
  } | null;
...
}

例如_innerStyle

animation: "flash"
animation-duration: "1s"
animation-iteration-count: "infinite"
background-color: "#ffffff"
box-shadow: "0px 2px 1px -1px rgba(0,0,0,.2), 0px 1px 1px 0px rgba(0,0,0,.14), 0px 1px 3px 0px rgba(0,0,0,.12)"
color: "#199719"

DOM 中的结果:

animation: 1s ease 0s infinite normal none running flash;

和变化

animation: "rubberBand"
animation-duration: "1s"
animation-iteration-count: "infinite"
background-color: "#b53b3b"
box-shadow: "0px 2px 1px -1px rgba(0,0,0,.2), 0px 1px 1px 0px rgba(0,0,0,.14), 0px 1px 3px 0px rgba(0,0,0,.12)"
color: "#199719"

DOM 中的结果:

0s ease 0s infinite normal none running flash

为什么animation-duration 突然被设置为0s?我正在打印 JSON 对象,它没有 0s 它有 1s

更奇怪的是,如果 animation-duration 是不同的值,它们会在更改时正确应用?!例如:1s2s 而不是 1s1s

我希望 dom 样式能够准确地反映样式对象。难道我做错了什么?!有没有办法调试 ngStyles 的行为?

【问题讨论】:

    标签: angular ng-style


    【解决方案1】:

    我认为这可能与更改检测有关,因为 _innerStyle 的引用(内存中的位置)没有改变,因此 Angular 没有启动更改检测。

    每次_innerStyle 更改您的 TypeScript/JavaScript 时,尝试像这样不可变地更新它:

    this._innerStyle = {
       ...this._innerStyle, // keep all of the old properties (spread operator)
      color: 'red',         // change the properties here though
      'background-color': red,
    };
    

    【讨论】:

    • 你是对的,但实际上我已经用传播运算符做到了这一点。问题出在我的 CSS 上,请参阅我的回答。
    【解决方案2】:

    我意识到animation 是一个简写属性。
    我真的很想使用animation-name

    如果我使用 animation 作为 css 属性,我需要构建速记值。

    通过使用各个动画属性,动画可以正确应用,并且不会被animation 速记属性覆盖。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多