Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create dynamic CSS style from string with Angular items

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

like image 325
Nasenbaer Avatar asked Sep 25 '26 19:09

Nasenbaer


1 Answers

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

like image 87
Tib Schott Avatar answered Sep 28 '26 23:09

Tib Schott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!