I am trying to load ace editor dynamically into my angular2 application at the click of a button but it looks like that ace editor is producing the following error on console:
Error: ace.edit can't find div #editor
Here is an example code:
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);
I want this code to work exactly in this position. Why ace editor can't find the id that I am giving to pre tag? I can see editor
id in the source code after bootstrapping the app. I re-produced the problem here on plunkr . You can monitor the console for the error message. Thanks in anticipation.
Update
I tried doing it this way
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);
but still no luck.
As I was playing along I thought may be ace editor is too quick to check the id before angular 2 manipulates the DOM :P. So I tried the setTimeout function and tried creating ace editor inside setTimeout callback function and guess what? it worked. Here is the working code
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);
and here is plunkr
我认为这可能有问题,因为你没有正确完成HTML,它期望一个带有editor
ID的div,如下所示:
<div id="editor" ace-editor [(text)]="text" style="height:150px;">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.