Moose
Moose

Reputation: 1317

How to generate unrendered HTML elements on web page with Angular 2.1.1 like stackoverflow?

What I am trying to do:

I am attempting to create a web page with Angular2 which shows HTML on the screen in much the same way many websites do such as stackoverflow, css-tricks, and and w3schools (to name a few). I would like to be able to copy the code and paste it somewhere else after its shown on screen.

What I know:

I have come to realize that it will probably be necessary to convert all of my opening tags ( i.e., < ) to &lt and to convert all of my closing tags ( i.e., > ) to &gt, however I am still not sure what the best way to interpolate some variables into the template.

For example, I have this in my template file:

<div>{{myTitle}}</div>
<div><p>{{mySubTitle}}</p></div>
<div>
<ul>
<li>{{item1}}</li>
<li>{{item2}}</li>
<li>{{item3}}</li>
</ul>
</div>

What I want to see (and be able to copy) in the browser:

<div>This is my title</div>
<div><p>This is my subtitle</p></div>
<div>
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Durian</li>
</ul>
</div>

Stack overflow makes this really easy and nice to accomplish by letting you highlight the code you want to display on screen and clicking the {} button in the editor. However, when I try using the <pre> and <code> tags in my Angular2 app, I do not get the same result, I cannot see the actual HTML elements like <div> and <li>.

Instead what I see is:

{{myTitle}}
{{mySubTitle}}
{{item1}}
{{item2}}
{{item3}}

I have used handlebarsjs in the past and am familiar with that library but I was under the impression that using Angular2 would eliminate the need for handlebarsjs. Does anyone know how to accomplish what I am trying to do in Angular2 without handlebarsjs?

Upvotes: 1

Views: 649

Answers (2)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657338

Use <pre> or <code> for HTML to become rendered verbatim.

<pre ngNonBindable>
  <div>{{'{{'}}myTitle{{'}}'}}</div>
  <div><p>{{'{{'}}mySubTitle{{'{{'}}</p></div>
  <div>
  <ul>
  <li>{{'{{'}}item1{{'{{'}}</li>
  <li>{{'{{'}}item2{{'{{'}}</li>
  <li>{{'{{'}}item3{{'{{'}}</li>
  </ul>
  </div>
</pre>

You need to escape { and } (for example like shown above)

Upvotes: 0

Adnan A.
Adnan A.

Reputation: 1982

For < and > you'll probably need to use &lt and &gt.

For the braces in template expressions you may want to use ngNonBindable directive.

<div ngNonBindable> {{myTitle}} </div>

Upvotes: 1

Related Questions