I'm trying to use Highlight JS in my Angular 2 app, and am having some trouble figuring out how to use it, when the codeblock is not static information. What I mean is, the code string comes from the server through an http get call.
So, if I have this:
export class WorkstationComponent implements OnInit {
private submission = new Submission();
private criteria = new Array<ExerciseCriteria>();
private codeString:string = `
/* HelloWorld.java
*/
public class HelloWorld
{
public static void main(String[] args) {
System.out.println("Hello World!");
}
}`;
constructor(private _router:Router, private submissionService:SubmissionService,
private activatedRoute:ActivatedRoute){}
@ViewChild('code') codeElement: ElementRef;
ngOnInit(){
this.activatedRoute.params
// (+) converts string 'id' to a number
.switchMap((params: Params) => this.submissionService.getSubmission(+params['id']))
.subscribe(data => this.success(data),
error => this.fail(error));
}
success(data:any){
this.submission = data;
this.criteria = data.criteria;
hljs.highlightBlock(this.codeElement.nativeElement);
}
There is no problem...

However, if i change to
success(data:any){
this.submission = data;
this.criteria = data.criteria;
this.codeString = data.code;
hljs.highlightBlock(this.codeElement.nativeElement);
}
I get this:

What am I doing wrong? The HTML is the same
<pre>
<code #code highlight class="java">
{{codeString}}
</code>
</pre>
highlightBlockis getting fire beforecodeStringbinding gets evaluated. You might need to wait for next tick and callhighlightBlockfunction. Like by doingsetTimeout(() => { hljs.highlightBlock(this.codeElement.nativeElement); },0);instead ofhljs.highlightBlock(this.codeElement.nativeElement);