1

How can I get a CSS in a string to dynamically paint an HTML element?

The HTML element must render a line of CSS code dynamically. the use of [style.etc], [ngStyle], [style], [ngStyle], [ng-class] does not work for me because I receive a string with CSS code from the backend, example:

style: "background: red; color: white;"

I can not use the following solution:

style: "{{style}}" nor [style] = "style" because I get an alert in the console that says:

WARNING: sanitizing unsafe style value background: network; color: white;

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

2 Answers 2

2

Creating method to bypass sanatizing unsafe will allow usage of stringed css

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

test button

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

test class with method that sanatizing unsafe value(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);
   }

}

Here you can read about creating safe pipes.

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

Sign up to request clarification or add additional context in comments.

Comments

0

you can also add:

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

If you want get color from some property in ts then remove ' characters and pass variable name e.g

     [style.color]="somePropertyWIthPrimaryColor"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.