我正面临着一个问题。我想在我的angular2视图中获得一个htmlelement这是我的视图
<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");
}
}发布于 2016-01-20 11:15:17
可能是这样的:
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'));
}
}这将从组件元素中定位编辑器元素。
发布于 2019-06-28 13:25:01
您可以使用Template reference variables <div #editor id="jsoneditor">
HTML
<p>
<button (click)="setJSON()">Set JSON</button>
<button (click)="getJSON()">Get JSON</button>
</p>
<div #editor id="jsoneditor">
</div>TS
export class AppComponent {
@ViewChild('editor') editor: ElementRef;
constructor(public element: ElementRef) {
}
setJSON() {
var json = {
"Array": [1, 2, 3],
"Boolean": true,
"Null": null,
"Number": 123,
"Object": { "a": "b", "c": "d" },
"String": "Hello World"
};
this.editor.nativeElement.innerHTML = json.String;
}
getJSON() {
alert("getJson");
}
}https://stackblitz.com/edit/angular-template-reference-variable?file=src/app/app.component.html
https://stackoverflow.com/questions/34890620
复制相似问题