【问题标题】:Angular 2 RC1 - Auto import all used components inside a base componentAngular 2 RC1 - 在基础组件中自动导入所有使用的组件
【发布时间】: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


    【解决方案1】:

    更新

    Angular2 final 不再支持。 见How to make directives and components available globally

    原创

    根据使用的内容,您无法导入。您可以做的是提供所有组件并允许在全球范围内提供它们

    export const MY_DIRECTIVES = [DirA, DirB, DirC];
    

    用户需要导入MY_DIRECTIVES并像使用它

    provide(PLATFORM_DIRECTIVES, {useValue: [MY_DIRECTIVES], multi: true})
    

    有关如何通过 RC.3 方式执行此操作,请参阅 Angular 2.0.0-rc.2: How to migrate PLATFORM_DIRECTIVES

    【讨论】:

    • 感谢您的快速回答!我被困在第二步,导入组件数组,您能否解释一下,那里发生了什么以及提供(...)或 PLATFORM_DIRECTIVES 来自哪里?再次感谢。
    • export const MY_DIRECTIVES ... 的文件需要导入所有组件并在数组中列出。用户需要将MY_DIRECTIVES导入到包含bootstrap(...)的文件中,并将最后一行代码添加到bootstrapp(AppComponent, [provide(PLATFORM_DIRECTIVES ...)])中。
    • 使用这种方法有缺点。 Angular 团队正在研究 tree-shaking,我很确定这不适用于这种方法,并且会导致超出必要的构建输出大小。您还应该支持组件用户仅导入组件的方法他们实际上想使用。因为这是在 Angular 中完成的,所以无论如何他们都习惯了。
    猜你喜欢
    • 2016-11-13
    • 1970-01-01
    • 2016-10-09
    • 2018-05-13
    • 2019-06-24
    • 1970-01-01
    • 2018-08-29
    • 1970-01-01
    • 2017-10-15
    相关资源
    最近更新 更多