【发布时间】: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