如何使用angular2和typescript在我的视图中获取指定的htmlelement
我面临一个问题。我想在angular2的视图中获得一个htmlelement 这是我的看法如何使用angular2和typescript在我的视图中获取指定的htmlelement,angular,Angular,我面临一个问题。我想在angular2的视图中获得一个htmlelement 这是我的看法 <p> <button (click)="setJSON()">Set JSON</button> <button (click)="getJSON()">Get JSON</button> </p> <div id="jsoneditor"> </div> 也许是这样的: import {
<p>
<button (click)="setJSON()">Set JSON</button>
<button (click)="getJSON()">Get JSON</button>
</p>
<div id="jsoneditor">
</div>
也许是这样的:
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'));
}
}
这将从组件元素中找到编辑器元素。您可以使用
HTML
ElementRef:表示视图中与注入、更改检测和渲染上下文关联的位置。但是我没有所有这些(注入等),我只需要告诉编辑器在哪里显示编辑器。nativeElement没有queryselector()方法。
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'));
}
}
<p>
<button (click)="setJSON()">Set JSON</button>
<button (click)="getJSON()">Get JSON</button>
</p>
<div #editor id="jsoneditor">
</div>
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");
}
}