我想获取DOM元素并在不使用ElementRef
的情况下初始化JSON编辑器。
import {Component, ViewChild} from 'angular2/core';
@Component({
selector: 'json-editor',
template: `
<div #container class="json-editor-container"></div>
`
})
export class JSONEditorComponent implements OnChanges {
@ViewChild('container') private container = null;
constructor() {
}
}
无论如何,this.container
仍为空。我写的代码的哪一部分是错的?
在访问ViewChild
属性之前,您必须确认视图已初始化。另外@VarChild
会返回ElementRef
,如果您想进一步处理它需要DOMElement,请使用nativeElement
Element
属性
import {Component, ViewChild} from 'angular2/core';
@Component({
selector: 'json-editor',
template: `
<div #container class="json-editor-container"></div>
`
})
export class JSONEditorComponent implements OnChanges {
@ViewChild('container') private container = null;
private isViewInitialized: boolean = false;
constructor() {
}
ngAfterViewInit() {
this.isViewInitialized = true;
}
triggeredFromParentComponentOrWhatever() {
if (this.isViewInitialized) {
// Should work
console.log(this.container.nativeElement);
}
// Might not work as view might not initialized
console.log(this.container.nativeElement);
}
}
答案 0 :(得分:1)
您无法在构造函数中访问container
。它仅在ngAfterViewInit()
ngViewInit() {
container.nativeElement...
}