Search code examples
angularsassangular7

Angular 7 - Inject new CSS to Component SCSS file


Suppose I dynamically inject new HTML in the DOM.

<div [innerHTML]="htmlCode | sanitizeHtml">
...
</div>

Within Tyescript:

htmlCode : string = '<svg class = "foobar"'>....'

How can I dynamically add a new class (in this case foobar) to the components scss file? Note that the class name can be different each time so I can't hard code it in


Solution

  • You can set the class using [ngClass] like this:

    <div [innerHTML]="htmlCode | sanitizeHtml" [ngClass]="dynamicClass">
    ...
    </div>
    

    Then in your ts file:

    htmlCode : string = '<svg class = "foobar"'>....'
    dynamicClass: string = 'yourClassName';
    

    Finally, if you want to set the styles dynamically, you can use [ngStyle] like this:

    <div [innerHTML]="htmlCode | sanitizeHtml" [ngClass]="dynamicClass" [ngStyle]="dynamicStyle">
    ...
    </div>
    

    Then in your ts file:

    htmlCode : string = '<svg class = "foobar"'>....'
    dynamicClass: string = 'yourClassName';
    dynamicStyle: string = {
        'color': 'red'
      }
    

    If you want to use a parameter or variable to set a style property you can do this:

    setCustomColor(color: string): {
          dynamicStyle: string = {
            'color': `${color}`
          }
    }