2017-04-09 163 views
0

我試圖在html中顯示代碼,並使用Google Code prettify來美化代碼。我幾乎接近完成我的要求,但是當我嘗試外部化文件並從中提取代碼時,它不起作用。谷歌代碼在Angular2中部分工作的美化代碼

這是我的ts代碼片段。

demoJavaCode: any; 
demoJavaCodeFromFile: any; 

ngOnInit() { 
    this.demoJavaCode = 
     `<pre><xmp class="prettyprint"> 
     public class A { 
      public static void main(String args[]) { 
      } 
     } 
     </xmp></pre>`; 
} 

ngAfterViewInit() { 
    PR.prettyPrint(); 
}` 

在模板中,我正在像這樣讀取它。

<p [innerHtml] ="demoJavaCode | trustedHtml"></p> 

它運作良好,只有當它使用trustedHTML管消毒,它突出顯示/美化它有代碼段。

但是,當我試圖將代碼外部化到具有完全相同代碼內容的外部文件時,它不起作用。

這是我的ts片段。

this._http.get("assets/java_code.txt").map(res => res.text()).subscribe(
     response => { 
     this.demoJavaCodeFromFile = response; 
     }, 
     error => { 
     this.componentErrorMessage = error; 
     }, 
    () => { 
     console.log('File successfully loaded..'); 
     } 
    ); 

這裏有什麼問題?任何指針和建議都會有所幫助。

+1

林假設「PR.prettyPrint( )'調用一個代碼漂亮的全局API?如果你在分配this.demoJavaCodeFromFile之後調用它,在訂閱的成功函數中? –

+0

@AhmedMusallam,它的確如此,它希望將代碼附加到文檔中,除非明確傳入根,並且它不會輸入shadowRoot或模板節點。請參閱[聲明](https://github.com/google/code-prettify/blob/master/src/prettify.js#L1530) –

回答

3

你應該叫PR.prettyPrint();ngAfterViewChecked組件lifecycle hook

裏面看看這個plnkr:https://plnkr.co/edit/wDJCKx3RjpJID2Nb6j2L?p=preview

這裏距離plnkr代碼:

//src/app.ts 
import {Component, NgModule, VERSION, AfterViewChecked} from '@angular/core' 
import { FormsModule } from '@angular/forms'; 
import {BrowserModule} from '@angular/platform-browser' 
import { HttpModule } from '@angular/http'; 
import { Http } from '@angular/http'; 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h2>Hello {{name}}</h2> 
     <button (click)="refresh()">refresh</button> 
     <div [innerHtml]="code"></div> 
    </div> 
    `, 
}) 
export class App implements AfterViewChecked { 
    name:string; 
    code: string; 
    constructor(private http: Http) { 
    this.name = `Angular! v${VERSION.full}`; 
    } 
    refresh(){ 
    this.http.get("javacode.html") 
    .subscribe(
     res => { 
     this.code = res._body; 
     }, 
    ()=>{}, 
    ()=>{}) 

    } 
    ngAfterViewChecked(){ 
     console.log('ngAfterViewChecked') 
     PR.prettyPrint(); 
    } 
} 

@NgModule({ 
    imports: [ BrowserModule, HttpModule, FormsModule], 
    declarations: [ App ], 
    bootstrap: [ App ] 
}) 
export class AppModule {} 
//-------------------------------------- 
//src/javacode.html 
<pre class="prettyprint"> 
    public class Cube { 

    int length; 
    int breadth; 
    int height; 
    public int getVolume() { 
     return (length * breadth * height); 
    } 
} 
</pre> 
+0

如何導入PR?我得到「找不到名字'PR'' – Wenneguen

+2

你不能」導入「它,因爲它不是一個模塊,你可以像聲明PR那樣聲明PR'var PR;'或者你可以像'var PR =窗口[ 「PR」]' –