【问题标题】:Use variables inside @component styles在@component 样式中使用变量
【发布时间】:2022-10-21 22:42:21
【问题描述】:

我想生成一些动态 CSS 并在 @component 的样式中使用它。我不确切知道如何传递该变量,并且想知道是否可以这样做。 这是使用变量“stylesArray”的一段代码。

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
    styles: stylesArray,
    encapsulation: ViewEncapsulation.None,
})
export class AppComponent {
    stylesArray: string[] = [
        // Generate some dynamic css here
    ];
}

【问题讨论】:

    标签: angular components


    【解决方案1】:

    您可以使用主机装饰器属性来做到这一点:

    @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.scss'],
        encapsulation: ViewEncapsulation.None,
        host: {
          '[style]': 'stylesArray'
        }
    })
    export class AppComponent {
        stylesArray: string = [
            // Generate some dynamic css here
            // for example:
            'display: block; background: red;'
        ];
    }
    

    【讨论】:

    • 感谢您的答复。但它会在运行时抛出错误error NG1010: Decorator host metadata must be an object. Value could not be determined statically. 而且 [style] 属性只接受表达式作为字符串而不是数组。
    • 是的,对不起,忘记引号:)
    • 不幸的是,这对我不起作用。我没有错误或什么的。我希望这个答案有一个示例,说明 stylesArray 的外观。
    • @William 在答案中添加示例
    猜你喜欢
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 2012-05-19
    相关资源
    最近更新 更多