How to display java code in ionic app?

how to display java code in ionic 2 app?

I would wrap it inside of <pre><code>...</code></pre>. That way indentation will be preserved and a monospace font should be used for better readability.

well its not helping me could you help with a code ?

I use highlightjs to highlight code in ionic

https://highlightjs.org/

Download the hightlightjs and put it in the assets Folder

image

Put this in the head of your index.html

<!--highlight.js Code Higlighter-->
  <link rel="stylesheet" href="assets/highlight/styles/default.css">
  <script src="assets/highlight/highlight.pack.js"></script>

Put this behind your Imports of your page

declare var hljs: any;

This is the function to higlight the Code:

highlightCode(){
    // console.log("highlightCode");
    var aCodes = document.getElementsByTagName('pre');
    for (var i=0; i < aCodes.length; i++) {
      hljs.highlightBlock(aCodes[i]);
    }
  }

Here the html

<pre><code class="java">{{yourJavaSourceCode}}</code></pre>

when to call this function

highlightCode(){
// console.log(“highlightCode”);
var aCodes = document.getElementsByTagName(‘pre’);
for (var i=0; i < aCodes.length; i++) {
hljs.highlightBlock(aCodes[i]);
}
}

If you have static Code on your page call it in

ionViewDidLoad()

If you create your Code dynamically call it when your Code is ready to be formatted.

okay thanks for the help i am reading code from firebase and it is displayed in a single line

1 Like

I used this

getting weird output

index.html

 <link rel="stylesheet"
  href="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@9.15.10/build/styles/default.min.css">

    <script src="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@9.15.10/build/highlight.min.js"></script>

view-code.page.ts

import { Component, OnInit } from '@angular/core';
declare var hljs: any;
@Component({
  selector: 'app-view-code',
  templateUrl: './view-code.page.html',
  styleUrls: ['./view-code.page.scss']
})
export class ViewCodePage implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  yourJavaSourceCode = 'Class TestJava \n { \n String name; int rollno; \n }'

 
  highlightCode(){
     console.log("highlightCode");
    var aCodes = document.getElementsByTagName('pre');
    for (var i=0; i < aCodes.length; i++) {
      hljs.highlightBlock(aCodes[i]);
    }
  }
}

view-code.page.html

<ion-header>
  <ion-toolbar>
    <ion-title>view-code</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <pre><code class="java">{{yourJavaSourceCode}}</code></pre>

  <ion-button (click)="highlightCode()" >Highlight</ion-button>
</ion-content>

please help me