简体   繁体   中英

Is there a way to to print the component raw code before rendered to the screen in Angular?

I am trying to build an angular UI component lib doc without using any third party document library like typedoc etc and found out it's hard to print out the raw component code example to screen, for example if I try:

<pre><code><some-component></some-component></code></pre>

The <some-component> will be rendered instead of showing the code. I generated an example here https://plnkr.co/edit/baaNxRX1K1H8ry9pwfBU?p=preview As you see, I tried to get the raw dom from the <ng-content> in <example-component> and the <child-component> is already rendered in raw dom which is not what I want.

Is there any way to print out the raw component code without putting it into a string like:

let codeString = '<child-component></child-component>'

Thank you!

If you want to show the selector, just go with

<code>{{ '<child-component></child-component>' }}</code>

Interpolated strings are not rendered as HTML and/or Angular syntax, they are just presented as is.

As to showing the component's class' code.... Though, I do not think it is entirely impossible (though you can probably show the compiled JS, not the original TypeScript code), but I think the safest and easiest solution is to just copy-paste the code into a string and interpolate it.

<code [innerText]="'<child-component></child-component>'"></code>

If you're project is built with webpack you can get the component's code with the raw-loader :

@Component({
    template: `
        <code>{{ componentString }}</code>
    `
})
export class AppComponent {
  componentString = require('!!raw-loader!./some.component.html');
}

For syntax highlighting use prismjs-loader . Here's a demo project .

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