Display raw html - Angular 6

Viewed 13797

I am looking to display the raw HTML code (example.component.html) below 'example works!'. The page should display the following:

example works!    
<p>   
  example works!
</p>

I can find various resources showing how this can be done using AngularJS but not Angular 6.

I have tried to use [innerHTML] but this didn't work.


<p>
  example works!
</p>

example.component.ts

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

@Component({
  selector: 'rt-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

app.component.html

<div style="text-align:center">
  <rt-example></rt-example>
</div>

OUTPUT . . link to image

3 Answers

You can use the ViewContainerRef to get the nativeElement, and get its innerHTML.

Just a warning : this won't be your HTML code, but the compiled code.

Here is an example : stackblitz

export class AppComponent  {
  htmlContent: string;
  constructor(private view: ViewContainerRef) {
    setTimeout(() => this.htmlContent = (view.element.nativeElement as HTMLElement).innerHTML);
  }
}

EDIT If you want the uncompiled code, you should use this notation : stackblitz

import { Component, ViewContainerRef } from '@angular/core';
import * as template from "./app.component.html";


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  htmlContent: string = template.default;
  constructor(private view: ViewContainerRef) {
  }
}

But I suggest you use the latest versions of typescript & Angular, since I'm not sure when it has been introduced.

Get a reference pointing to that component using ViewChild, like

export class AppComponent  {
  @ViewChild(ExampleComponent, { read: ElementRef }) exampleComponent;
}

Then you can access its HTML with nativeElement.innerHTML.

So you could change your app.component.html to this:

<div style="text-align:center">
  <rt-example></rt-example>
</div>

{{exampleComponent.nativeElement.innerHTML}}

In HTML, you need to use entities to show the reserved characters.

<p>example works!</p>

<code>&lt;p&gt;example works!&lt;/p&gt;</code>

For example:

&amp; is equivalent to &

&lt; is equivalent to <

&gt; is equivalent to >

However solution using angular would be:

Component:

export class SomeComponent  {
  code :string = `<p>example</p>`
}

HTML:

<code>{{this.code}}</code>

OR Use InnerText instead of InnerHTML

<p [innerText]="code"></p>

https://stackblitz.com/edit/angular-5cpmcr

Related