【问题标题】:CSS dynamic value in angular角度中的CSS动态值
【发布时间】:2019-06-12 00:02:57
【问题描述】:

如何获取字符串中的 CSS 以动态绘制 HTML 元素?

HTML 元素必须动态呈现一行 CSS 代码。 使用[style.etc][ngStyle][style][ngStyle][ng-class] 对我不起作用,因为我从后端收到带有 CSS 代码的字符串,例如:

风格:"background: red; color: white;"

我无法使用以下解决方案:

style: "{{style}}" 也不是 [style] = "style" 因为我在控制台中收到一条警告:

警告:清理不安全的样式值背景:网络;颜色:白色;

<button type="button"
  *ngFor="let controlHTML of buttons"
  style="{{controlHTML.attributes.style}}"> HelloWorld
</button>

【问题讨论】:

    标签: css angular dynamic styles rendering


    【解决方案1】:

    创建绕过清理不安全的方法将允许使用字符串 css

            <button type="button"
                *ngFor="let controlHTML of buttons"
                [style]="trustedSecurity(controlHTML.attributes.style)"> HelloWorld
            </button>
    

    测试按钮

             <button type="button"              
               [style]="trustedSecurity(style)"> HelloWorld
             </button>
    

    使用清理不安全值(css)的方法测试类

     import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser';
    
     export class TestClass{
    
       style = "background: red; color: white;";
    
       constructor(private _sanitizer: DomSanitizer) {}
    
       trustedSecurity(style) {
          return this._sanitizer.bypassSecurityTrustStyle(style);
       }
    
    }
    

    您可以在此处阅读有关创建安全管道的信息。

    https://medium.com/@swarnakishore/angular-safe-pipe-implementation-to-bypass-domsanitizer-stripping-out-content-c1bf0f1cc36b

    【讨论】:

      【解决方案2】:

      您还可以添加:

           [style.background-color]="'red'"
           [style.color]="'white'"
      

      如果您想从 ts 中的某些属性中获取颜色,则删除 ' 字符并传递变量名,例如

           [style.color]="somePropertyWIthPrimaryColor"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-07
        • 2020-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多