2

I want to give users of my application the possibility to set plain CSS styles and those style definitions should be applied immediately to some HTML elements.

For example, I have a textarea bound to a model in my component:

<textarea #customCss></<textarea>

In the same component, I defined a HTML element and for that HTML element, I want to give the user the possibility to assign plain CSS and allow the user to immediately preview the styled element. So basically, I would expect something like the following (which isn't working since the style property is readonly):

<div style="{{ customCss.value }}">CUSTOM STYLED DIV</div>

Therefore, when a user enters background:black;color:red; in the textarea, I would expect that the HTML for the styled element would be rendered as:

<div style="background:black;color:red;">CUSTOM STYLED DIV</div>

I don't see any chance to use the ng-style directive here directly since it would expect some JSON code and not plain CSS code.

So how can I tackle this problem in Angular4?

2 Answers 2

2

Probably the easiest way is to just bind to the attribute:

<div [attr.style]="customCss.value">CUSTOM STYLED DIV</div>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that pointed me to the right direction, I posted the final solution.
2

Niles advice got me back on the right track, thanks for that.

I already tried [attr.style]="..." before but without success but the problem was that the resulting CSS rendered to "unsafe" (at least in Safari), see this Github issue.

Therefore, I wrote my own Pipe using the DomSanitizer in order to get this work. Here is the code:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({name: 'safeStyle'})
export class SafeStylePipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) {}

    transform(style) {
        return this.sanitizer.bypassSecurityTrustStyle(style);
    }
}

Our custom pipe can then be used as usual with:

<div [attr.style]="customCss.value|safeStyle">CUSTOM STYLED DIV</div>

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.