在组件访问本地变量角2失败 [英] Access local variable in Component fails in Angular 2

查看:255
本文介绍了在组件访问本地变量角2失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要得到的DOM元素并初始化一个JSON编辑器,而无需使用 ElementRef

code:

 进口{组件,ViewChild}从'angular2 /核心;@零件({
    选择:JSON编辑器,
    模板:`
        <的div #container的类=JSON-编辑容器>< / DIV>
    `
})
出口类JSONEditorComponent实现OnChanges {
    @ViewChild(容器)私营集装箱= NULL;    构造函数(){
    }
}

不管 this.container 如何,仍是空。其中code的一部分,我写的是错的?


解决方案:

在您访问 ViewChild 属性,必须确认该视图已初始化。此外 @VarChild 收益 ElementRef ,如果你要处理它进一步要求一个DOMElement,请使用 nativeElement 属性,它是一个元素

 进口{组件,ViewChild}从'angular2 /核心;@零件({
    选择:JSON编辑器,
    模板:`
        <的div #container的类=JSON-编辑容器>< / DIV>
    `
})
出口类JSONEditorComponent实现OnChanges {
    @ViewChild(容器)私营集装箱= NULL;
    私人isViewInitialized:布尔= FALSE;    构造函数(){
    }    ngAfterViewInit(){
        this.isViewInitialized = TRUE;
    }    triggeredFromParentComponentOrWhatever(){
        如果(this.isViewInitialized){
            //应该工作
            的console.log(this.container.nativeElement);
        }        作为视图可能未初始化//可能无法正常工作
        的console.log(this.container.nativeElement);
    }
}


解决方案

您无法访问容器在构造函数中。它仅是前几个 ngAfterViewInit设置()

  ngViewInit(){
  container.nativeElement ...
}

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

解决方案

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

ngViewInit() {
  container.nativeElement...
}

这篇关于在组件访问本地变量角2失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆