首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用angular2和typescript在我的视图中获取指定的htmlelement

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

Stack Overflow用户
提问于 2016-01-20 10:40:30
回答 2查看 29.3K关注 0票数 3

我正面临着一个问题。我想在我的angular2视图中获得一个htmlelement这是我的视图

代码语言:javascript
复制
<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,以告诉它在哪里呈现编辑器。

这是我的班级:

代码语言:javascript
复制
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");
    }
}
EN

回答 2

Stack Overflow用户

发布于 2016-01-20 11:15:17

可能是这样的:

代码语言:javascript
复制
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'));
    }
}

这将从组件元素中定位编辑器元素。

票数 6
EN

Stack Overflow用户

发布于 2019-06-28 13:25:01

您可以使用Template reference variables <div #editor id="jsoneditor">

HTML

代码语言:javascript
复制
<p>
    <button (click)="setJSON()">Set JSON</button>
    <button (click)="getJSON()">Get JSON</button>
</p>
<div #editor id="jsoneditor">
</div>

TS

代码语言:javascript
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34890620

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档