【问题标题】:Access local variable in Component fails in Angular 2在 Angular 2 中访问组件中的局部变量失败
【发布时间】:2016-06-16 05:36:11
【问题描述】:

我想在不使用ElementRef 的情况下获取 DOM 元素并初始化 JSON 编辑器。

代码:

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 仍然为空。我写的代码哪一部分错了?


解决方案:

在访问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);
    }
}

【问题讨论】:

  • 好吧,您实际上并没有将任何东西传递给@ViewChild,您是否尝试过将“容器”添加到您的指令中并尝试过?然后,您随后将容器实例化为 null,这将始终使其为 null。你也可以解释一下你想要做什么吗?
  • 你觉得这个答案怎么样?
  • 我仍然不完全确定您要做什么,您正在查看的问题似乎是通过输入从“父”元素获取数据并将其应用于HTML
  • 这里也是 Angular2 为 @ViewChild 的工作原理提供的 plunker plnkr.co/edit/eNsFHDf7YjyM6IzKxM1j?p=preview

标签: angularjs angular angular2-directives


【解决方案1】:

您不能在构造函数中访问container。仅在ngAfterViewInit()之前设置

ngViewInit() {
  container.nativeElement...
}

【讨论】:

  • ngAfterViewInit() { console.log(this.container); }其实还是不行
  • 您是否收到任何错误消息?我不认为这有什么不同,但你可以尝试删除= null 吗?您的应用程序中可能还有其他问题。无论如何,您想对元素引用做什么?你不能用绑定来做吗?
  • 到底是什么修复了它?
  • 我很抱歉我犯了错误,它有效。很抱歉在没有确认的情况下发表评论...
猜你喜欢
  • 2016-07-16
  • 1970-01-01
  • 1970-01-01
  • 2018-07-12
  • 1970-01-01
  • 2017-02-25
  • 1970-01-01
  • 2016-07-28
  • 1970-01-01
相关资源
最近更新 更多