0

Hello I am trying to add html from a file that is returned from the api, this is working. what I am needing help with is when I add an inline style it doesn't work, but if I create a class in the style.css it and add it to the html it then works.

All of this said, I need to get inline style working. I would like to get <span style="color:red;">I am red</span> working.

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <button (click)="onClick()">Click To Add Html</button>
    </div>
    <div *ngIf="html!==''" [innerHtml]="html"></div>
  `,
})
export class App {
  name:string;
  html:string=null;

  const htmlConst:string = `<span style="color:red;">I am red</span>`;
  /*
  I have tried [style] = "color:red;"
  style="color:red;"
  */
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  onClick():void{
    if(this.html !== ''){
      this.html= this.htmlConst;
    }
    else{
      this.html = '';
    }
  }
}

any advise would be helpful.

3xGuy
  • 2,235
  • 2
  • 29
  • 51

1 Answers1

4
    import { Component,ViewEncapsulation } from '@angular/core';

    @Component({
      selector: 'my-app',
      template: `
        <div>
          <h2>Hello {{name}}</h2>
          <button (click)="onClick()">Click To Add Html</button>
        </div>
        <div *ngIf="html!==''" [innerHtml]="html"></div>
      `,
    encapsulation: ViewEncapsulation.None
    })

Please refer from https://toddmotto.com/emulated-native-shadow-dom-angular-2-view-encapsulation

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Sundhar
  • 449
  • 1
  • 5
  • 9
  • Can you add an explanation as to how it solves the problem here instead of just a reference link? – Suraj Rao Sep 16 '17 at 04:39
  • reference link have detailed explanation.this question is already answered in stack overflow https://stackoverflow.com/questions/44210786/style-not-working-for-innerhtml-in-angular-2-typescript – Sundhar Sep 16 '17 at 04:43
  • Then you should flag as duplicate – Suraj Rao Sep 16 '17 at 04:44
  • thank you for the reference, however this still isn't working. Yes, this is a very similar question, but I would like to use inline css rather than changing the css file on all of the different ways to use this. – 3xGuy Sep 18 '17 at 11:30