Angular 2 RC1 - Auto import all used components inside a base component

I'm quite new to Angular2 with TypeScript and have a problem that I am not able to solve for a long time now:

I want to provide the user some kind of small components toolkit that they use inside the view, to build a (real) small app. Therefore I need an app component that is able to go through all its child elements when initializing and check for each of its children, if it is already imported or not. If not then import it in order to enable its usage.

Saying it in html / code - this is what I want to acchieve:

<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>


The basic idea to solve this is:

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
           // --------------- 
        }
}


So basically the steps 1 and 2 (maybe 4 as well) are the critical steps that I did not manage to solve in some way. I'm really getting desperate :(

ANY HELP IS HIGHLY RECOMMENDED! Thanks in advance guys!

Note: Thanks to custom naming / structuring conventions the tag name will be sufficient to define the correct path to the component, so e.g. the tag name "my-test" will statically lead to the path "../elements/my-test/my-test.component.ts".

Answer1:

<strong>update</strong>

Not supported in Angular2 final anymore. See How to make directives and components available globally

<strong>original</strong>

You can't import depending on what's used. What you can do, is to provide all components and allow to provider them globally like

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

The user needs to import MY_DIRECTIVES and use it like

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

For how to do this the RC.3 way see Angular 2.0.0-rc.2: How to migrate PLATFORM_DIRECTIVES

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:Angular 2 RC1 - Auto import all used components inside a base component