2016-01-20 29 views
2

我正面临一个问题。我想获得一个HTMLElement在我看来,在angular2 这是我的看法如何在我的视图中使用angular2和typescript获取指定的hmmlelement

<p> 
<button (click)="setJSON()">Set JSON</button> 
<button (click)="getJSON()">Get JSON</button> 
</p> 
<div id="jsoneditor"> 


</div> 

我想访问jsoneditor在我的课,并把它传递给我的JSONEditor https://github.com/josdejong/jsoneditor/blob/master/docs/api.md告诉它渲染编辑

这是我的课

export class JsonComponent { 

container: HTMLElement; 
editor1: JSONEditor; 
options; 
constructor(public router: Router, public element: ElementRef) { 

    this.container = this.element.nativeElement 

    this.options = { "mode": "tree", "search": true };    
    this.editor1 = new JSONEditor(this.container,this. options); 
    var json = { "Array": [1, 2, 3], "Boolean": true, "Null": null, "Number": 123, "Object": { "a": "b", "c": "d" }, "String": "Hello World" }; 
    this. editor1.set(json); 
    this. editor1.expandAll(); 
}     

setJSON() { 
    alert("setJson"); 
     } 
getJSON() { 
    alert("getJson"); 
} 

}

+0

ElementRef:表示具有与其关联的注入,更改检测和呈现上下文的视图中的位置。但我没有所有这些(注入等)我只需要告诉编辑器在哪里显示编辑器。 –

回答

3

也许是这样的:

import {Component, ElementRef, Inject, OnInit} from 'angular2/core'; 

@Component({ 
    selector: 'my-component', 
    templateUrl: './my-template.html' 
}) 
export class SomeComponent implements OnInit { 
    elementRef: ElementRef; 

    constructor(@Inject(ElementRef) elementRef: ElementRef) { 
     this.elementRef = elementRef; 

    } 

    ngOnInit() { 

      console.log(this.elementRef.nativeElement.querySelector('#jsoneditor')); 
    } 
} 

这应该从组件元素中找到编辑器元素。

+0

没有工作nativeElement没有queryselector()方法。 –

+0

尝试上面的代码 – TGH

+0

这工作谢谢。 –

相关问题