简体   繁体   中英

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

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

Plunker example

See also

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM