Search code examples
htmlcssangulartypescriptinline

How to display string HTML containing inline style tag from angular component


I want to show a saved HTML containing inline style tag, from an angular component, I have tried encapsulation: ViewEncapsulation.None, but it's not working.

Component:

@Component({
  selector: 'app-page-content',
  templateUrl: './page-content.component.html',
  styleUrls: ['./page-content.component.css'],
  encapsulation: ViewEncapsulation.None,
})

Get data from HTTP get in the ts component:

description=<p class="ql-direction-rtl ql-align-right" style="text-align: center;"><strong><span style="color: #236fa1;">test</span></strong></p>

Showing the data: <div [innerHtml]=description></div>


Solution

  • Angular doesn't allow you to directly pass styles into a variable because of security issues. So you have to explicitly tell it that your string is safe.

    You do it as follows:

    import {DomSanitizer} from '@angular/platform-browser'
    
    

    ....

    export class AppComponent {
      description;
      constructor(private sanitizer: DomSanitizer) {
        this.description = sanitizer.bypassSecurityTrustHtml(`<p class="ql-direction-rtl ql-align-right" style="text-align: center;"><strong><span style="color: #236fa1;">test</span></strong></p>`)
      }
    }