tom10271
tom10271

Reputation: 4649

Access local variable in Component fails in Angular 2

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);
    }
}

Upvotes: 0

Views: 2290

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657228

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

ngViewInit() {
  container.nativeElement...
}

Upvotes: 1

Related Questions