Angular2 innerHtml binding remove style attribute

<>

This question already has an answer here:

Answers


You can leverage DomSanitized to avoid it.

The easiest way is to create custom pipe like:

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

@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform  {
  constructor(private sanitized: DomSanitizer) {}
  transform(value) {
    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

So you can use it like:

<div [innerHtml]="html | safeHtml"></div>

Plunker Example


I improved the example of yurzui a bit by completing the needed imports:

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

@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform  {
  constructor(private sanitized: DomSanitizer) {}
  transform(value) {
    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

I also had to add the class in my app.module.ts file

import ...
import {SafeHtmlPipe} from "./pipes/safehtml.pipe";
@NgModule({
    declarations: [
        AppComponent,
        ...,
        SafeHtmlPipe  <--
    ],
    imports: [...],
    providers: [...],
    bootstrap: [AppComponent]
})
export class AppModule {
}

Note that the sanitizer has a few methods for trusting content e.g.

return this.sanitizer.bypassSecurityTrustStyle(value);
return this.sanitizer.bypassSecurityTrustHtml(value);
return this.sanitizer.bypassSecurityTrustXxx(value); // - see docs [1]

via https://stackoverflow.com/a/41089093/142714

So, bypassSecurityTrustStyle may also be what you want here, as this will show inline styles within your HTML content (value).

[1] docs: https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html


Angular 2 aims for a more declarative approach, so directly manipulating HTML is often discouraged.

I believe that (almost) all HTML manipulations are patched to be filtered by angular's DOM sanitization. As you can imagine style attributes aren't white-listed for span elements, in fact, span has no allowed attributes at the moment.


Need Your Help

Mocking Controller Instantiation In Angular Directive Unit Test

javascript angularjs unit-testing jasmine karma-runner

I am unit testing an Angular directive and would like to mock or stub in some way the instantiation of the named controller in the unit test.

How do I hook into the action method for an iPad popover toolbar button?

ipad uipopovercontroller popover uisplitview

I am using the split view template to create a simple split view that has, of course, a popover in Portrait mode. I'm using the default code generated by template that adds/removes the toolbar item...