我試圖在我的Angular 2應用程序中使用Highlight JS,並且在代碼塊不是靜態信息時遇到了一些麻煩。我的意思是,代碼字符串通過http get調用來自服務器。在Angular 2中使用Highlight JS
所以,如果我有這樣的:
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);
}
是沒有問題的......
但是,如果我改變
success(data:any){
this.submission = data;
this.criteria = data.criteria;
this.codeString = data.code;
hljs.highlightBlock(this.codeElement.nativeElement);
}
我得到這個:
我在做什麼錯? 的HTML是一樣的
<pre>
<code #code highlight class="java">
{{codeString}}
</code>
</pre>
我的猜測是'highlightBlock'之前'codeString'越來越火綁定被評估。您可能需要等待下一個勾號並調用'highlightBlock'函數。就像通過'setTimeout(()=> {hljs.highlightBlock(this.codeElement.nativeElement);},0);'而不是'hljs.highlightBlock(this.codeElement.nativeElement);' –