Angular2 innerHtml binding remove style attribute

This question already has an answer here:

  • In RC.1 some styles can't be added using binding syntax 1 answer

  • You can leverage DomSanitized to avoid it. The easiest way is create custom pipe like:

    import { DomSanitizer } from '@angular/platform-browser'
    
    @Pipe({ name: 'safeHtml'})
    export class SafeHtmlPipe implements PipeTransform  {
      constructor(private sanitized: DomSanitizer) {}
      transform(value) {
        return this.sanitized.bypassSecurityTrustHtml(value);
      }
    }
    

    So you can use it:

    <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 {
    }
    

    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.

    链接地址: http://www.djcxy.com/p/22878.html

    上一篇: 为什么在控制器中操纵DOM是一件坏事?

    下一篇: Angular2 innerHtml绑定删除样式属性