Angular2递归模板在JavaScript [英] Angular2 Recursive Templates in javascript
问题描述
我一直在努力遵循本教程创建嵌套树视图。本教程是打字稿,当我试图做类似的事情在JavaScript与Angular2。
I have been trying to follow this tutorial to create a nested tree view. The tutorial is in typescript while I am trying to do a similar thing in javascript with Angular2.
在打字稿code,树视图组件看起来就像这样:
In the typescript code, the tree-view component looks like so:
import {Component, Input} from 'angular2/core';
import {Directory} from './directory';
@Component({
selector: 'tree-view',
templateUrl: './components/tree-view/tree-view.html',
directives: [TreeView]
})
export class TreeView {
@Input() directories: Array<Directory>;
}
在JavaScript的应该转换为:
In javascript that should convert to:
TreeView = ng.core
.Component({
selector: 'tree-view',
templateUrl: './components/tree-view/tree-view.html',
directives: [TreeView],
inputs: ['directory'],
})
.Class({
constructor: function() {
},
});
然而,javascript中引发以下错误:
However, javascript throws the following error:
例外:观未定义意外的指导价值
组件的功能(){
EXCEPTION: Unexpected directive value 'undefined' on the View of component 'function () {'
我相信这是因为我打电话指令:[TreeView控件] TreeView控件已经完全确定了。如果我删除指令行,错误消失。但是,我不知道为什么它会在打字稿,而不是JavaScript的工作,如果只是打字原稿编译为JavaScript。 <一href=\"https://github.com/thelgevold/angular-2-samples/blob/3b93bd7649fec29d01d6f6e2d1ecbe033c1ec6bc/components/tree-view/tree-view.js\"相对=nofollow>这是从打字稿code编译JavaScript的。我不知道我错过了什么。任何帮助将是超级AP preciated。
I believe it's because I'm calling directives: [TreeView] before TreeView has been fully defined. If I remove that directive line, the error goes away. However, I don't know why it would work in typescript and not javascript if typescript simply compiles to javascript. This is the compiled javascript from the typescript code. I'm not sure what I'm missing. Any help would be super appreciated.
推荐答案
这个问题已经回答了几次
This question has been answered a few times
所有类首先不悬挂。从 MDN
First of all classes are not hoisted. Quoting from MDN
函数的声明和类声明之间的一个重要区别是,函数声明悬挂和类声明都没有。你首先需要声明你的类,然后访问它[...]
An important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not. You first need to declare your class and then access it [...]
有关 forwardRef 文档说。
有关例如,当这是我们需要参考为DI的目的令牌被声明forwardRef被使用,但还没有定义。当还没有定义,我们创建查询时所使用的标记它也可用于
For instance, forwardRef is used when the token which we need to refer to for the purposes of DI is declared, but not yet defined. It is also used when the token which we use when creating a query is not yet defined.
所以,这是增加容易 forwardRef
您code
So it's as easy as adding forwardRef
to your code
directives : [ng.core.forwardRef(function() { return TreeView; })]
您可以阅读更多关于此主题
You can read more about this subject
- Forward references in Angular 2
- Others questions from StackOverflow
这篇关于Angular2递归模板在JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!