【问题标题】:How do I interpolate JS variables into css classes?如何将 JS 变量插入 css 类?
【发布时间】:2016-10-18 19:36:13
【问题描述】:

所以在 ng1 中,我可以执行以下操作:

angular.module('foo').component('foo', {
template:
    `<style type="text/css">
        .branding-color {
            color: {{ $ctrl.brandingColor }} !important;
        }

        .branding-color-after:after {
            background-color: {{ $ctrl.brandingColor }} !important;
        }

        .branding-color-before:before {
            background-color: {{ $ctrl.brandingColor }} !important;
        }

        .branding-color-border-before:before {
            border-color: {{ $ctrl.brandingColor }} !important;
        }

        .branding-color-bg {
            background-color: {{ $ctrl.brandingColor }};
        }

        button.button-primary, span.button-primary, a.button-primary, div.button-primary, .button-primary {
            background-color: {{ $ctrl.brandingColor }};
        }

        .button-primary.ty-sticky:enabled {
            border: 1px solid {{ $ctrl.brandingColor }} !important;
        }
    </style>`,
controller(API) {
    const defaultBrandingColor = 'white';

    API.Foobar.getStuff().then((response) => {
        this.brandingColor = _.get(response.data, 'brandingColor', defaultBrandingColor); // return a hex code
    });
},
});

我正在尝试模仿相同的行为,但无法让它发挥作用。我尝试在组件模板中使用 标记并使用组件的样式元数据,但在这两种情况下,ng2 都不会插入我的brandingColor。

知道如何解决这个问题吗?或者,我很乐意接受任何其他允许我为全局 css 类提供插值颜色的解决方案。

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    Angular2 不支持。

    使用

    [ngClass]="{'class1': boolValue1, 'class2': boolValue2 }"
    

    ngClass 提供的任何其他变体。

    【讨论】:

    • 你的建议是完全不同的。我想创建那些不消耗它们的类
    • 您也可以使用ngStyle,但您不能在 CSS 中使用绑定,因为这不受支持。他们希望最终支持 CSS 变量。
    • 嗯,我担心这就是答案。猜猜我必须走好路'document.createElement
    【解决方案2】:

    如果你使用``你可以像这样传递变量

    let var = "#000000";
    var css = `body { background: ${var} }`
    

    CSS可以通过这种方式传递给Component

    @Component({
        templateUrl: './login.component.html',
        styles: [
            `
                .grid { height: 90vh }
                .column { max-width: 450px }
                .form { text-align: left }
            `
        ]
    })
    

    【讨论】:

    • 下一步会是什么?这不能回答有关 angular2 的问题
    • 感谢您的努力,但我认为您应该再次阅读该问题
    猜你喜欢
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 2013-10-08
    • 2021-09-08
    • 2023-03-14
    • 2014-10-16
    • 1970-01-01
    • 2013-02-20
    相关资源
    最近更新 更多