如何使用 angular2 和 typescript 在我的视图中获取指定的 htmlelement

2024-01-29

我面临一个问题。我想在 angular2 的视图中获取 htmlelement 这是我的观点

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

</div>

我想访问类中的 jsoneditor 并将其传递给我的 JSONEditorhttps://github.com/josdejong/jsoneditor/blob/master/docs/api.md 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");
    }
}

也许是这样的:

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'));
    }
}

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 angular2 和 typescript 在我的视图中获取指定的 htmlelement 的相关文章

随机推荐