angular2 programmatically import components from resource files

强颜欢笑 提交于 2019-12-06 14:14:06

问题


Angular2 rc.4 - rc.5

Can we import components programmatically ?

for example if i have following import statements i want to convert

import {HelloComponent} from './hello.component';
import {IncComponent} from './inc.component';

is it possible to import components on runtime using system.import from the resource file as following ? any suggestion is appreciated

I have an array let routes: RouterConfig = [];

 let routeArr =[
    {path: 'hello', component:'HelloComponent', resource:'./hello.component'},
    {path:'inc', component:'IncComponent', resource:'./inc.component'}
    ];
 // injecting router object
 constructor(private router: Router){
}
    // iterating routeArr and creating RouteConfig objects
    routeArr.forEach((route : any) => {

    // import components programmatically on run time ?
     System.import(route.resource).then(

    m => {
    // create route config object and add in routes object
    routes.push({
    path: route.path
    component: m[route.component]
    });

    }
    )

});
// load all routes which we just created
router.resetConfig(routes);

回答1:


Surprisingly code in the questions worked :D use the code and enjoy dynamic route addings



来源:https://stackoverflow.com/questions/38860071/angular2-programmatically-import-components-from-resource-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!