0

我想获取 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);
    }
}
4

1 回答 1

1

您无法container在构造函数中访问。它只是在之前设置ngAfterViewInit()

ngViewInit() {
  container.nativeElement...
}
于 2016-03-03T04:33:28.037 回答