2016-04-01 71 views
3

我試圖動態加載的王牌編輯到我angular2應用程序在一個按鈕的點擊,但它看起來像王牌編輯器是生產上的控制檯以下錯誤:Angular2 - 動態加載王牌編輯

Error: ace.edit can't find div #editor

這裏是一個示例代碼:

main.ts

import {Component} from 'angular2/core'; 
import {bootstrap} from 'angular2/platform/browser'; 

@Component({ 
    selector: 'app', 
    template: `<div [innerHTML]="html" ></div> 
    <button class="btn btn-primary" (click)="addAce()" >Add Ace</button>` 
}) 
class MainApp{ 

    public html = ""; 

    constructor(){} 

    addAce(){ 

    this.html = "<pre style='height:100vh' id='editor' ></pre>"; 

    var editor = ace.edit("editor"); 
    editor.setTheme("ace/theme/twilight"); 
    editor.getSession().setMode("ace/mode/javascript"); 
    } 
} 
bootstrap(MainApp); 

我想這個代碼在這個位置正好工作。爲什麼ace編輯器找不到我給pre標籤的id?在引導應用程序後,我可以在源代碼中看到editor id。我重新制作了問題here on plunkr。您可以監視控制檯的錯誤消息。感謝預期。

更新

我試圖做這種方式

import {Component} from 'angular2/core'; 
import {bootstrap} from 'angular2/platform/browser'; 

@Component({ 
    selector: 'app', 
    template: `<button class="btn btn-primary" (click)="addAce()" >Add Ace</button> 
    <div><pre style='height:100vh' id='editor' ></pre></div>` 
}) 
class MainApp{ 
    public aceId = ""; 

    constructor(){} 

    addAce(){ 

    this.aceId = "editor"; 

    var editor = ace.edit("editor"); 
    editor.setTheme("ace/theme/twilight"); 
    editor.getSession().setMode("ace/mode/javascript"); 
    } 
} 
bootstrap(MainApp); 

但仍沒有運氣。

回答

2

當我一直在玩,我認爲可能是ace編輯器太快以至於在角度2操縱DOM之前檢查ID:P。所以我嘗試了setTimeout函數,並嘗試在setTimeout回調函數內部創建ace編輯器並猜測是什麼?有效。這裏是工作的代碼

import {Component} from 'angular2/core'; 
import {bootstrap} from 'angular2/platform/browser'; 

@Component({ 
    selector: 'app', 
    template: `<button class="btn btn-primary" (click)="addAce()" >Add Ace</button> 
    <div><pre style="height:100vh;" [id]="aceId" ></pre></div>` 
}) 
class MainApp{ 
    public aceId = ""; 

    constructor(){} 

    addAce(){ 

    this.aceId = "editor"; 

    setTimeout(function(){ 
     var editor = ace.edit("editor"); 
     editor.setTheme("ace/theme/twilight"); 
     editor.getSession().setMode("ace/mode/javascript"); 
    },0); 
    } 
} 
bootstrap(MainApp); 

here is plunkr

+1

不覺得自己是最佳的解決方案,雖然,因爲它可能需要更長的時間超過100ms的時候。 – Chrillewoodz

+0

是的,我知道,但現在它似乎是唯一的方法。等待其他解決方案。 – essaji

0

我想這可能是有問題的,因爲你沒有足夠的HTML得當,它期待與editor ID的DIV,像這樣:

<div id="editor" ace-editor [(text)]="text" style="height:150px;">