【问题标题】:Angular 2+ CSS Custom Properties (variables) with Renderer带有渲染器的 Angular 2+ CSS 自定义属性(变量)
【发布时间】:2018-11-24 07:02:16
【问题描述】:

我正在尝试将 Vanilla JavaScript 代码转换为 Angular 2+。

在 Javascript 中,我有这样的声明:

document.documentElement.style.setProperty(`--${cssVariableName}`, value);

在 Angular 中,我发现复制上述语句的唯一方法是:

renderer.setProperty(document.documentElement, 'style', `--${cssVariableName}: ${value}`);

问题:如果我在不同时间动态设置了多个自定义属性(--cssVariable1、--cssVariable2...)。 Angular 渲染器将覆盖样式属性,而不是附加到样式属性。

渲染器可以用来实现这个功能吗?如果没有,是否有在 Angular 中使用 CSS 自定义属性的首选方式?谢谢!

【问题讨论】:

标签: javascript css angular angular-renderer2 angular-renderer


【解决方案1】:

尝试使用setStyle方法

renderer.setStyle(document.documentElement, `--${cssVariableName}`, `${value}`);

【讨论】:

  • setStyle 将属性添加到元素的样式标签并添加。但是,对于自定义属性,该操作将被忽略,并且不会添加该属性。示例:'--background', 'green' // Invalid'background', 'green' // Valid
  • 请参阅下面@vikey 的回答。对于这些情况,需要将第三个(也是可选的)参数设置为 2。我刚刚测试了它,我可以确认它有效
【解决方案2】:

您可以使用 [ngStyle]。你不需要使用渲染器。

在您的控制器中,您可以拥有一个具有您想要应用的 css 属性的对象。

像这样。

props = {'color': 'red', 'font-size': '18px'};

然后在您的 html 中,您可以在 ngStyle 中使用它来将这些属性应用于元素。

<div [ngStyle]="props">Great example</div>

希望对你有帮助。

【讨论】:

    【解决方案3】:

    尝试使用Renderer2对象setStyle方法

    /**
     * Implement this callback to set a CSS style for an element in the DOM.
     * @param el The element.
     * @param style The name of the style.
     * @param value The new value.
     * @param flags Flags for style variations. No flags are set by default. enum: 1 or 2, 1: Marks a style as important.   2: Marks a style as using dash case naming (this-is-dash-case).
     */
    abstract setStyle(el: any, style: string, value: any, flags?: RendererStyleFlags2): void;
    

    你需要这个

     renderer.setStyle(document.documentElement, `--${cssVariableName}`, `${value}`, 2);
    

    【讨论】:

    • 你是救生员! :D 我完全错过了那里的标志参数,浪费了一个小时挠头!
    • 这个解决方案对我来说很好用!这里的标志参数 2 很重要!
    猜你喜欢
    • 2019-04-12
    • 1970-01-01
    • 2020-04-06
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 2011-03-20
    • 1970-01-01
    相关资源
    最近更新 更多