Angular 2+ ngStyle绑定与css对象具有重复属性

时间:2018-02-21 01:01:02

标签: angular typescript

我正在使用ngStyle属性绑定我的HTML元素来绑定我的Angular组件中的动态样式,如下所示:

example.component.ts

.spinnerStyle = {
            'background': this.color,
            'background': `-moz-linear-gradient(left, ${this.color} 10%, rgba(255,128,0, 0) 42%)`,
            'background': `-webkit-linear-gradient(left, ${this.color} 10%, rgba(255,128,0, 0) 42%)`,
            'background': `-o-linear-gradient(left, ${this.color} 10%, rgba(255,128,0, 0) 42%)`,
            'background': `-ms-linear-gradient(left, ${this.color} 10%, rgba(255,128,0, 0) 42%)`,
            'background': `linear-gradient(to right, ${this.color} 10%, rgba(255,128,0, 0) 42%)`
        }

example.component.html

<div class="loader" [ngStyle]="spinnerStyle">Loading...</div>

我们可以看到我的typescript文件有一个表示我的CSS样式的对象。它是一个有效的CSS,但是无效的打字稿对象,因为它有重复的标识符。由于这个原因,我的编译失败了。什么应该是替代方法?

1 个答案:

答案 0 :(得分:0)

好的,我为我的样式对象做了一个解决方法,首先将其创建为字符串文字,然后将其转换为JSON对象:

this.spinnerStyle = JSON.parse(`{ "background": "${this.color},background: -moz-linear-gradient(left, ${this.color} 10%, rgba(255,128,0, 0) 42%)",
            "background": "-webkit-linear-gradient(left, ${this.color} 10%, rgba(255,128,0, 0) 42%)",
            "background": "-o-linear-gradient(left, ${this.color} 10%, rgba(255,128,0, 0) 42%)",
            "background": "-ms-linear-gradient(left, ${this.color} 10%, rgba(255,128,0, 0) 42%)",
            "background": "linear-gradient(to right, ${this.color} 10%, rgba(255,128,0, 0) 42%)"
        }`);

它就像一个魅力......