【发布时间】:2016-10-25 12:02:05
【问题描述】:
我对使用 TypeScript 的 Angular2 还很陌生,并且有一个我很长时间无法解决的问题:
我想为用户提供一些他们在视图中使用的小组件工具包,以构建一个(真正的)小应用程序。因此,我需要一个能够在初始化时遍历其所有子元素的应用程序组件,并检查其每个子元素是否已导入。如果没有,则导入它以启用它的使用。
用 html / code 说 - 这就是我想要实现的:
<test-auto-import>
<!-- freely use custom components, because the test auto import element
will automatically take care of the imports when initializing -->
<some-custom control="that is acutally not imported"></some-custom>
<another-unimported></another-unimported>
</test-auto-import>
解决这个问题的基本思路是:
import { Component, OnInit } from '@angular/core'
@Component({
selector: 'test-auto-import',
templateUrl: 'test-auto-import.html',
styleUrls: ['test-auto-import.css']
})
class TestAutoImportComponent implements OnInit
{
ngOnInit() {
// run through children and getting their tag names
let app = document.getElementsByTagName('test-auto-import');
let children = app.childNodes;
let importNames = '';
// so iterate now:
for(let i =0; i< children.length; i++)
{
let child = children[i];
// ---------------
// todo:
// 1. import the component from generate path by tag name
// 2. get the @Component directives array
// 3. check whether the name is in it
// 4. if not, add it
// ---------------
}
}
所以基本上第 1 步和第 2 步(也可能是第 4 步)是我无法以某种方式解决的关键步骤。我真的越来越绝望了:(
强烈推荐任何帮助! 提前谢谢各位!
注意:由于自定义命名/结构约定,标签名称足以定义组件的正确路径,例如标签名称“my-test”将静态指向路径“../elements/my-test/my-test.component.ts”。
【问题讨论】:
标签: angular