Reputation: 4649
I want to get the DOM element and initialize a JSON Editor without using 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() {
}
}
No matter how, this.container
is still null. Which part of code I wrote is wrong?
Before you access the ViewChild
attribute, you must confirm the view has initialized. Also @VarChild
returns ElementRef
, if you want to process it further requires DOMElement, please use nativeElement
attribute which is a 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);
}
}
Upvotes: 0
Views: 2290
Reputation: 657228
You can't access container
in the constructor. It is only set just before ngAfterViewInit()
ngViewInit() {
container.nativeElement...
}
Upvotes: 1