Angular 4 Output Complete HTML Syntax code in HTML as raw text

徘徊边缘 提交于 2019-12-07 11:28:39

问题


I have scoured the possible answers and none of them work. All the innerHTML and PRE tag examples are fine with code or text, but NOT with HTML. Here is EXACTLY what I want to put into a variable:

<div [ngStyle]="{'display':'flex', 'flex-direction':'column', 'width': '100vw', 'height': '100vh'}">
  <top-header>
    <a class="topHeaderItem" (click)="goToHome()">Home</a>
    <a class="topHeaderItem" (click)="gotoTOC()">Contents</a>
  </top-header>

AND THAT is precisely what I want to show up on the screen - every single character because it is a tutorial example.

Here's my agony. My HTML:

1
<div [innerHTML]="code1">
</div>
<hr>
2
<div>
<pre>
  <code [innerHTML]="code1"></code>
</pre>
</div>
<hr>
3
<div [innerHTML]=code1>
</div>

My component.ts:

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

@Component({
  selector: 'cs-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent {
  code1 = `
<div [ngStyle]="{'display':'flex', 'flex-direction':'column', 'width': '100vw', 'height': '100vh'}">
  <top-header>
    <a class="topHeaderItem" (click)="goToHome()">Home</a>
    <a class="topHeaderItem" (click)="gotoTOC()">Contents</a>
  </top-header>
  `

   constructor() {
  }
}

And now my pathetic output:


回答1:


The innerHTML is if you want to actually show HTML that is inserted in the DOM as part of the document.

You want the normal {{ code1 }} syntax which will encode the variable for displaying.

Adding a code and a pre will style it the way you want (or you can do the same through CSS by setting the css of the container to have white-space:pre)

<div><code><pre>{{code1}}</pre></code></div>

example at https://plnkr.co/edit/cVnQZeWnqJCYTBmndmB6?p=preview




回答2:


Binding with [innerHTML] will interpret the HTML. If you want to show the HTML code, you could use [innerText] instead, or simply use string interpolation as @Vega noted. That will properly escape the HTML.

<div>{{ code1 }}</div>

// or

<div [innerText]="code1"></div>

Binding to [innerText] will preserve the line breaks.



来源:https://stackoverflow.com/questions/46911008/angular-4-output-complete-html-syntax-code-in-html-as-raw-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!