iniravpatel
iniravpatel

Reputation: 1643

Inline styling in Angular2

I am getting blocks of HTML codes from HTTP calls which has inline styling in it. I put the HTML blocks in a variable and insert it on my page with [innerHTML] but I cannot see the style reflected in the inserted HTML block. Does anyone have any suggestion how I can achieve this?

@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>";
  }
}

In the above example 1234 is not coming red.

Here is the plnkr

Upvotes: 4

Views: 5313

Answers (2)

Darshita
Darshita

Reputation: 746

Change your code in plunker as shown below :

import {Component, NgModule,ElementRef,ViewChild} from '@angular/core'

@Component({
  selector: 'my-app',
  template: `
    <input type="text" [(ngModel)]="html">
    <div [innerHtml]="html" #value>
    </div>
  `,
})
export class App {
  name:string;
  html: string;

  @ViewChild("value") el : ElementRef

  constructor() {
    this.name = 'Angular2'
    this.html = "1234";
  }
  ngOnInit(){
    this.el.nativeElement.style.color = "red";
  }
}

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657516

  constructor(private sanitizer:DomSanitizer) {
    this.html = sanitizer.bypassSecurityTrustHtml("<span style=\"color:red;\">1234</span>");

Plunker example

See also

Upvotes: 6

Related Questions