Search code examples
javascripthtmlangular-material2angular5prismjs

HTML code is not rendering, just being displayed as plaintext


I have some HTML, but for some reason it's showing up as plaintext and it's not rendering.

This is what it looks like:

enter image description here

The HTML for this is like so:

<div>
  <mat-card>
    <button mat-raised-button>Copy Code to Clipboard</button>
    <mat-card-title>Card with title and footer</mat-card-title>
    <mat-card-subtitle>Subtitle</mat-card-subtitle>
    <mat-card-content>
      <code>{{muchoCodo}}</code>
    </mat-card-content>
    <mat-card-actions>
      <button mat-button>LIKE</button>
      <button mat-button>SHARE</button>
    </mat-card-actions>
    <mat-card-footer>
      Card Footer
    </mat-card-footer>
  </mat-card>

</div>

{{muchoCodo}}

The string data is being rendered as the muchoCodo variable. Here is my Angular code:

import {Component, OnInit} from '@angular/core';
declare var Prism;

import 'prismjs';
import 'prismjs/themes/prism-okaidia.css'
import 'prismjs/components/prism-handlebars.min.js'
import 'prismjs/components/prism-lua.min.js'

@Component({
  selector: 'app-generated-code',
  templateUrl: './generated-code.component.html',
  styleUrls: ['./generated-code.component.scss'],
  styles: [`
    mat-card { margin:2em; }
  `]
})
export class GeneratedCodeComponent implements OnInit {

  muchoCodo: string;

  constructor() {

    this.muchoCodo = Prism.highlight(`

    import suman = require('suman');
    const {Test} = suman.init(module);

    Test.create((b, it, before) => {

      it('bahru', t => {

      });

    });


    `, Prism.languages.javascript);

  }

  ngOnInit() {
  }

}

Anybody know how I can get the string to render as HTML?


Solution

  • In order to render the text as HTML, you have to bind to the innerHTML property of the desired container element.

    <mat-card-content>
      <code [innerHTML]="muchoCodo"></code>
    </mat-card-content>
    

    Keep in mind that this is a potential security issue and you should trust the HTML content you are going to render on the page.