3

I'm using Angular 2+ [innerHTML] input to insert HTML formatting including style tags.

In my template I have something like:

<span [innerHTML]="someVar"></span>

In my component, I have:

someVar = `<span style="background-color:#990000">test</span>`;

I get a warning:

WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).

In the output, the inserted span in intact, minus the style attribute.

So I used a pipe from this post:

https://stackoverflow.com/questions/37076867/

It looks like:

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

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

  transform(html): SafeHtml {
    // return this.sanitizer.bypassSecurityTrustStyle(style);
    return this.sanitizer.bypassSecurityTrustHtml(html);
    // return this.sanitizer.bypassSecurityTrustScript(value);
    // return this.sanitizer.bypassSecurityTrustUrl(value);
    // return this.sanitizer.bypassSecurityTrustResourceUrl(value);
  }
}

This yields no difference than before, though I'm not sure I'm using that the right way...

How can I get Angular to retain my style attribute using innerHTML?

2
  • 1
    Look at this post: stackoverflow.com/a/34467699/5468463 Commented Sep 11, 2017 at 6:35
  • 1
    Thanks. What I had should have worked. I don't know why it didn't the first time... Anyhow, updated the pipe in my post. Commented Sep 11, 2017 at 6:44

2 Answers 2

12

You're nearly there. You just need to make sure that you are using your pipe for your HTML string.

Example pipe:

import {Pipe} from '@angular/core'; 
import {DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl} from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe {

constructor(protected sanitizer: DomSanitizer) {}

  transform(htmlString: string): any {
    return this.sanitizer.bypassSecurityTrustHtml(htmlString);
  }
}

Example usage:

<span [innerHTML]="someVar | safe"></span>

Hope this helps!

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

1 Comment

Not recommended at all. You'll open yourself to XXS attacks
4

Either you use this filter, or you do it in your code.

To apply the filter, you need to use it in your HTML like this :

<span [innerHTML]="someVar | safeStyle"></span>

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.