Home > Blockchain >  Create dynamic CSS style from string with Angular items
Create dynamic CSS style from string with Angular items

Time:09-17

When using dynamic class with property "Style". Including for example item.Style="color: red"

it is working fine. But Visual Studio code throws error } expectedcss(css-rcurlyexpected) or similar. Result is correct but Designer does not work: Result

The label-result is 'red' in my case but how to avoid the syntax errors?

enter image description here

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

error on ngStyle

CodePudding user response:

ngStyle needs key value as object. In that case a dictionary is needed. Try my style string to dictionary parser.

You can use it like default css and use all known basic CSS- Syntax.

Example for item.Style

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

Angular

<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;
  }

Result

result for stlye

CodePudding user response:

Update: You can use pipe and attr.style binding for this (Which would also scale well through your entire app):

  1. Create a pipe as sanitizer
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. Register the pipe within your module
@NgModule({
  declarations: [SafePipe],
})
export class AppModule {}
  1. Use it everywhere...

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;"};
}

Result:

enter image description here

Demo: https://stackblitz.com/edit/angular-playground-iodcgy?file=app/app.component.ts

References:

  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


The value for the [ngStyle] must be key-value pairs or an expression that returns key-value pairs. You can use both style and [ngStyle] respectively. Angular would then merge them, e.g.:

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

result:

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

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

CodePudding user response:

This should fix it:

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