ngNonBindable not working in angular-2

2019-09-13 05:39发布

问题:

I want to display source code using google pretty print inside my app component. I am using ngNonBindable in 'pre' tag. but it give error on compile/page run.

zone.js:388Unhandled Promise rejection: Template parse errors:
Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.) ("
<div id="routerContainer">
    <router-outlet></router-outlet>
</div>[ERROR ->]"): AppComponent@37:6
Invalid ICU message. Missing '}'. ("
<div id="routerContainer">
    <router-outlet></router-outlet>
</div>[ERROR ->]"): AppComponent@37:6 ; Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:(…) Error: Template parse errors:
Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.) ("

My html code is

<pre class="prettyprint"  ngNonBindable>
    import {Component} from '@angular/core';                                    
</pre>

回答1:

Check Demo Here : https://plnkr.co/edit/PPChFemU6HnXDBQohIsj?p=preview


To display .ts code, You can use DomSanitizer to display what you want.

import {Component, NgModule, Pipe, PipeTransform} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { FormsModule } from '@angular/forms';

import { DomSanitizer, SafeHtml } from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <pre [innerHtml]="html">
    </pre>
  `,
})
export class App {
  name:string;
  html: SafeHtml;
  constructor(private sanitized: DomSanitizer) {

    this.html = `
    import {Component, NgModule, Pipe, PipeTransform} from '@angular/core'
    import {BrowserModule} from '@angular/platform-browser'
    import { FormsModule } from '@angular/forms';

    @Component({
    selector: 'my-app',
    template:' 
         <span> Angular2 </span>
    '
    })
    `;


    this.html = this.sanitized.bypassSecurityTrustHtml(this.html);
  }

}


标签: angular