BBaysinger
BBaysinger

Reputation: 6857

Using Angular 2+ [innerHTML] to add html including style attributes

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?

Upvotes: 3

Views: 8017

Answers (2)

Rob Bailey
Rob Bailey

Reputation: 981

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!

Upvotes: 12

user4676340
user4676340

Reputation:

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>

Upvotes: 4

Related Questions