user7161814
user7161814

Reputation:

How to Display Typescript code in Html

I want to display a component's code in a Html template, Not the value generated by the code but the actual code.

like this

   import { Injectable } from '@angular/core';
    import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
    import {CompetitionService} from "../shared/competition.service";
    import {Observable} from "rxjs";


    @Injectable()
    export class TableResolve implements Resolve<any> {

    constructor(private competitionService:CompetitionService) {}

    resolve(route: ActivatedRouteSnapshot):Observable<> {
      return this.competitionService.getTeams(route.params['id']);
      }
      }

This whole code like they show in stackoverflow in the question section.I tried using <pre> and <code> but none seem to work ,i am getting this error in console.

Error: Template parse errors: Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.)

But if i have to escape it for all { it is problematic please help ?

Upvotes: 8

Views: 9556

Answers (1)

Rahul Kumar
Rahul Kumar

Reputation: 5229

Use a variable in your ts file that contains all the code and display it in html using this {{stringThatContainsAllTheCode}}

I think the simplest way is to use [innerHTML]="varContainingCode" and hold the code in the components class

<pre>
  <code [innerHTML]="code"></code>
</pre>
export class AppComponent {
  code = `   //type script code`
}

Or if you don't want to use this library call ng2-prism can be useful.

This is a Angular2 codeblock highlighting component library.

Upvotes: 7

Related Questions