Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 innerHtml binding remove style attribute [duplicate]

Tags:

angular

styles

My problem, that when I use innererHtml binding - angular2 remove all styles attributes. It's important for me, bacause in my task - html is generated on server-side with all styles. Example:

@Component({   selector: 'my-app',   template: `     <input type="text" [(ngModel)]="html">     <div [innerHtml]="html">     </div>   `, }) export class App {   name:string;   html: string;   constructor() {     this.name = 'Angular2'     this.html = "<span style=\"color:red;\">1234</span>";   } } 

But in DOM I see only 1234 and this text is not red.

http://plnkr.co/edit/UQJOFMKl9OwMRIJ38U8D?p=preview

Thank you!

like image 857
SamProf Avatar asked Sep 21 '16 23:09

SamProf


2 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

like image 128
yurzui Avatar answered Nov 10 '22 01:11

yurzui


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 { } 
like image 27
mvermand Avatar answered Nov 10 '22 02:11

mvermand