我有一个 <span>
我想应用动态样式。
样式存储在类 css 中 string
变量,可以是任意的,例如
myStyle = 'color: white; font-weight: bold;'
或
myStyle = 'background-color: red;'
我希望它能像这样工作
<span style="{{myStyle}}">
但它没有。
我尝试了不同的选择,但由于不同的原因似乎都不适合我:
- 我不能将样式放在 .css 文件中并使用类名,因为样式是以上述字符串的形式来自服务器
- 使用
[style.color]
等不适合我,因为我不知道风格可以是什么 - 使用
[ngStyle]
不适合我,因为它需要像{'color': 'red', 'font-weight': 'bold'}
这样的对象我只有字符串
我将样式存储在字符串中的原因是因为我需要在服务器上生成的 HTML 中应用它,我只需将该字符串传递给速度模板中的占位符变量。
我几乎确信它不能按照我想要的方式完成,但可能我忽略了一些解决方案。
最佳答案
您只需要 DomSanitizer
和 bypassSecurityTrustStyle
Component side :
import { DomSanitizer } from '@angular/platform-browser';
constructor(private doms : DomSanitizer) {}
newStyle = 'background-color:red';
safeCss(style) {
return this.doms.bypassSecurityTrustStyle(style);
}
Template side :
<p [style]="safeCss(this.newStyle)">
Start editing to see some magic happen :)
</p>
关于css - 是否可以在 Angular 中将动态样式作为字符串应用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47350066/