Skip to content

Instantly share code, notes, and snippets.

@ysyun
Created July 19, 2016 01:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ysyun/60af0b62dcd68f53ebfe964fb828dc11 to your computer and use it in GitHub Desktop.
Save ysyun/60af0b62dcd68f53ebfe964fb828dc11 to your computer and use it in GitHub Desktop.
angular2 dynamic component loading using ComponentResolver
{
"stage": 1,
"modules": "system"
}
import {Component} from '@angular/core'
import { bootstrap } from '@angular/platform-browser-dynamic';
import { WidgetContainer } from './widget-container.ts'
@Component({
selector: 'my-app',
template: '<widget-container></widget-container>',
directives: [WidgetContainer]
})
class App {}
bootstrap(App)
import {
Component,
ComponentResolver,
ViewContainerRef,
ViewChild,
DynamicComponentLoader,
Input
} from '@angular/core';
class MyComponentLoader {
loadComponentConfig(url){
return fetch(url)
.then(res => res.json())
.then(componentList => Promise.all(componentList.map(this.loadComponent.bind(this))))
}
loadComponent(configObject){
return System
.import(configObject.path)
.then(componentModule => componentModule[configObject.component])
}
}
@Component({
selector: 'widget-container',
template: `<div #content></div>`,
providers: [MyComponentLoader]
})
export class WidgetContainer {
@ViewChild('content', {read: ViewContainerRef})
container: ViewContainerRef;
@Input()
src: string = 'config.json';
constructor(
private loader: MyComponentLoader,
private resolver: ComponentResolver
){}
ngOnInit() {
this
.loader
.loadComponentConfig(this.src)
.then(components => Promise.all(components.map(this.loadComp.bind(this))))
}
private loadComp( comp: Component, index: number) {
return this.resolver.resolveComponent(comp).then((factory) =>
this.container.createComponent(factory, index, this.container.injector))
}
}
import {Component, View} from '@angular/core';
@Component({
selector: 'widget1',
template: `<div>i'm widget 1</div>`
})
export class Widget1 {}
import {Component, View} from '@angular/core';
@Component({
selector: 'widget2',
template: `<div>i'm widget 2</div>`
})
export class Widget2 {}
import {Component, View} from '@angular/core';
@Component({
selector: 'widget3',
template: `<div>i'm widget 3</div>`
})
export class Widget3 {}
[
{"component": "Widget1", "path": "./app/widget1.ts"},
{"component": "Widget2", "path": "./app/widget2.ts"},
{"component": "Widget3", "path": "./app/widget3.ts"}
]
<!DOCTYPE html>
<html>
<head>
<title>Angular 2 QuickStart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="https://npmcdn.com/es6-shim@0.35.0/es6-shim.min.js"></script>
<script src="https://npmcdn.com/zone.js@0.6.12?main=browser"></script>
<script src="https://npmcdn.com/reflect-metadata@0.1.3"></script>
<script src="https://npmcdn.com/systemjs@0.19.27/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>
<!--
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->
/**
* PLUNKER VERSION (based on systemjs.config.js in angular.io)
* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
*/
(function(global) {
var ngVer = '@2.0.0-rc.1'; // lock in the angular package version; do not let it float to current!
//map tells the System loader where to look for things
var map = {
'app': 'app',
'@angular': 'https://npmcdn.com/@angular', // sufficient if we didn't pin the version
'angular2-in-memory-web-api': 'https://npmcdn.com/angular2-in-memory-web-api', // get latest
'rxjs': 'https://npmcdn.com/rxjs@5.0.0-beta.6',
'ts': 'https://npmcdn.com/plugin-typescript@4.0.10/lib/plugin.js',
'typescript': 'https://npmcdn.com/typescript@1.8.10/lib/typescript.js',
};
//packages tells the System loader how to load when no filename and/or no extension
var packages = {
'app': { main: 'main.ts', defaultExtension: 'ts' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { defaultExtension: 'js' },
};
var ngPackageNames = [
'common',
'compiler',
'core',
'http',
'platform-browser',
'platform-browser-dynamic',
'router',
'router-deprecated',
'upgrade',
];
// Add map entries for each angular package
// only because we're pinning the version with `ngVer`.
ngPackageNames.forEach(function(pkgName) {
map['@angular/'+pkgName] = 'https://npmcdn.com/@angular/' + pkgName + ngVer;
});
// Add package entries for angular packages
ngPackageNames.forEach(function(pkgName) {
// Bundled (~40 requests):
packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' };
// Individual files (~300 requests):
//packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
});
var config = {
// DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
transpiler: 'ts',
typescriptOptions: {
tsconfig: true
},
meta: {
'typescript': {
"exports": "ts"
}
},
map: map,
packages: packages
}
System.config(config);
})(this);
/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
},
"exclude": [
"node_modules",
"typings/main",
"typings/main.d.ts"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment