0

I want to get the DOM element and initialize a JSON Editor without using ElementRef.

Code:

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?


Solution:

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);
    }
}
tom10271
  • 4,222
  • 5
  • 33
  • 62
  • Well for one you are not actually passing anything to @ViewChild, have you tried adding 'container' to your directives and trying it? Also you are then instantiating container to null afterwards, which will always make it null. Also could maybe you explain exactly what you are trying to do? – Morgan G Mar 03 '16 at 04:06
  • http://stackoverflow.com/questions/34517969/access-a-local-variable-from-the-template-in-the-controller-in-angular2 – tom10271 Mar 03 '16 at 04:07
  • What do you think about the answer? – tom10271 Mar 03 '16 at 04:08
  • I'm still not entirely sure what you are trying to do, what it appears the question you are looking at was trying to do was get data from a 'parent' element via input and apply it to the HTML – Morgan G Mar 03 '16 at 04:26
  • Also here is the plunker put out by Angular2 for how @ViewChild works http://plnkr.co/edit/eNsFHDf7YjyM6IzKxM1j?p=preview – Morgan G Mar 03 '16 at 04:27
  • I want to get the DOM element and initialize a JSON Editor – tom10271 Mar 03 '16 at 04:30

1 Answers1

1

You can't access container in the constructor. It is only set just before ngAfterViewInit()

ngViewInit() {
  container.nativeElement...
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567