【问题标题】:Create dynamic CSS style from string with Angular items使用 Angular 项从字符串创建动态 CSS 样式
【发布时间】:2021-09-09 23:43:06
【问题描述】:

使用具有“样式”属性的动态类时。包括例如item.Style="color: red"

它工作正常。 但是 Visual Studio 代码会抛出错误 } expectedcss(css-rcurlyexpected) 或类似错误。 结果正确但 Designer 不起作用:

在我的情况下,标签结果是“红色”,但如何避免语法错误?

错误:ERROR Error: Cannot find a differ supporting object 'color: #DFFDD00;'

【问题讨论】:

    标签: angular ionic-framework visual-studio-code


    【解决方案1】:

    ngStyle 需要 key + value 作为 object。在这种情况下,需要字典。试试我的样式字符串到字典解析器。

    您可以像使用默认 CSS 一样使用它,并使用所有已知的基本 CSS 语法。

    item.Style 示例

    background-color:blue;font-size: 22px;color:red;
    

    角度

    <div [ngStyle]="setStyle(item.Style)">Hello World</div>
    

    TypeScript

    private setStyle(value: string): unknown {
        console.log(value);
        if (value == "") return null;
        //Example: value = "background-color:blue";
        var properties = value.split(";");
        var keyValuePairs = {};
        properties.forEach(o => {
          var key = String(o.split(":")[0]).trim();
          var value = String(o.split(":")[1]).trim();
          if (key.length > 0) {
            keyValuePairs[key] = value;
          }
        })
        console.log("keyValuePairs: " + JSON.stringify(keyValuePairs));
        return keyValuePairs;
      }
    

    结果

    【讨论】:

      【解决方案2】:

      更新:您可以为此使用 pipeattr.style 绑定 (这也可以很好地扩展到您的整个应用程序):

      1. 创建一个管道作为消毒剂
      import { Pipe, PipeTransform } from '@angular/core';
      import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
      
      @Pipe({
        name: 'safe'
      })
      export class SafePipe implements PipeTransform {
      
        constructor(protected sanitizer: DomSanitizer) {}
       
       public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
          switch (type) {
                  case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
                  case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
                  case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
                  case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
                  case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
                  default: throw new Error(`Invalid safe type specified: ${type}`);
              }
        }
      }
      
      1. 在你的模块中注册管道
      @NgModule({
        declarations: [SafePipe],
      })
      export class AppModule {}
      
      1. 到处使用它...

      app.component.html

      <p [attr.style]="key.Style | safe:'style'">{{key.Style}}</p>
      

      app.component.ts

      export class AppComponent {
        key = {Style: "background-color:blue;font-size: 22px;color:red;"};
      }
      

      结果:

      演示:https://stackblitz.com/edit/angular-playground-iodcgy?file=app%2Fapp.component.ts

      参考资料:

      1. https://angular.io/api/platform-browser/DomSanitizer

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

      3. https://ultimatecourses.com/blog/angular-pipes-custom-pipes


      [ngStyle] 的值必须是键值对或返回键值对的表达式。 您可以分别使用style[ngStyle]。然后 Angular 会合并它们,例如:

      key = {Style: { 'font-size': '18px' }}
      
      <p style="color: red" [ngStyle]="key.Style"></p>
      

      结果:

      <p style="color: red; font-size: 18px;"></p>
      

      演示:https://stackblitz.com/edit/angular-playground-jd2g2t?file=app/app.component.html

      【讨论】:

      • 使用 style={{myItem.Style}} 时出错 = 设计上的语法错误。使用[ngStyle]="myItem.Style" = Cannot find a differ supporting object color: #D0D000;时出错
      • 也许我只是不明白。我将[ngStyle]="key.Style" 和值设置为{Style: { 'color: #D0D000; font-size': '18px' }},它不会改变任何样式。
      • @Nasenbaer 检查这个演示。我的意思是:stackblitz.com/edit/angular-playground-jd2g2t?file=app/…
      • 顺便说一句,您提供的值看起来不正确。它应该是{Style: { 'color': '#D0D000', 'font-size': '18px' }}。这部分{ 'color': '#D0D000', 'font-size': '18px' } 必须遵循 JavaScript 键值对象约定。
      • 谢谢,我明白了。问题是,我无法在任何数据库中将此解决方案作为字符串读/写。使用 typescript 解析器方法的解决方案允许不解释任何关于 ngModel 的内容,因为字符串是默认 css,可以在数据库中写入和回读。
      【解决方案3】:

      这应该可以解决它:

      [ngStyle]="'color: #000000; ' + key.Style"
      

      【讨论】:

      • 感谢您的快速响应。在这种情况下,错误出现在运行时:ERROR Error: Cannot find a differ supporting object 'color: #D00000;'
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      • 2019-07-20
      • 2021-07-19
      相关资源
      最近更新 更多