角形 2.3.0 (2016-12-07)
要獲得所有詳細信息,請檢查:
在行動中看到這一點:
校長:
1)創(chuàng)建模板
2)創(chuàng)建組件
3)創(chuàng)建模塊
4)編譯模塊
5)創(chuàng)建(和緩存)ComponentFactory
6)使用Target創(chuàng)建一個實例
快速概述如何創(chuàng)建組件
createNewComponent (tmpl:string) {
@Component({
selector: 'dynamic-component',
template: tmpl,
})
class CustomDynamicComponent implements IHaveDynamicData {
@Input() public entity: any;
};
// a component for this particular template
return CustomDynamicComponent;}
一種將組件注入NgModule的方法
createComponentModule (componentType: any) {
@NgModule({
imports: [
PartsModule, // there are 'text-editor', 'string-editor'...
],
declarations: [
componentType ],
})
class RuntimeComponentModule
{
}
// a module for just this Type
return RuntimeComponentModule;}
如何創(chuàng)建ComponentFactory
(并緩存它)
public createComponentFactory(template: string)
: Promise<ComponentFactory<IHaveDynamicData>> {
let factory = this._cacheOfFactories[template];
if (factory) {
console.log("Module and Type are returned from cache")
return new Promise((resolve) => {
resolve(factory);
});
}
// unknown template ... let's create a Type for it
let type = this.createNewComponent(template);
let module = this.createComponentModule(type);
return new Promise((resolve) => {
this.compiler .compileModuleAndAllComponentsAsync(module)
.then((moduleWithFactories) =>
{
factory = _.find(moduleWithFactories.componentFactories
, { componentType: type });
this._cacheOfFactories[template] = factory;
resolve(factory);
});
});}
如何使用上述結(jié)果的代碼片段
// here we get Factory (just compiled or from cache)
this.typeBuilder .createComponentFactory(template)
.then((factory: ComponentFactory<IHaveDynamicData>) =>
{
// Target will instantiate and inject component (we'll keep reference to it)
this.componentRef = this
.dynamicComponentTarget .createComponent(factory);
// let's inject @Inputs to component instance
let component = this.componentRef.instance;
component.entity = this.entity;
//...
});
包含所有細節(jié)的完整描述讀這里,或觀察工作實例