我想获取 DOM 元素并在不使用ElementRef
.
代码:
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
仍然是null。我写的代码哪一部分是错误的?
解决方案:
在访问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);
}
}