2016-01-20 30 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

這工作謝謝。 –

相關問題