我想动态创建一个模板。这应该用于在运行时构建componenttype
并将其放置(甚至替换)到宿主组件的某个位置。
在RC4之前,我一直使用componentresolver
,但在RC5中,我得到以下消息:
ComponentResolver is deprecated for dynamic compilation.
Use ComponentFactoryResolver together with @NgModule/@Component.entryComponents or ANALYZE_FOR_ENTRY_COMPONENTS provider instead.
For runtime compile only, you can also use Compiler.compileComponentSync/Async.
我找到了这个文档(Angular 2同步动态组件创建)
并且明白我可以使用任何一种
ComponentFactoryResolver
的动态NGIF
。如果在@component({entrycomponents:[comp1,comp2],...})
中传递已知组件-我可以使用.resolveComponentFactory(componentToRender);
编译器
进行实时运行时编译...但问题是如何使用那个编译器
?上面的注释说我应该调用:compiler.compileComponentSync/async
-那么如何调用呢?
例如。我想为一种设置创建(基于一些配置条件)这种模板
<form>
<string-editor
[propertyName]="'code'"
[entity]="entity"
></string-editor>
<string-editor
[propertyName]="'description'"
[entity]="entity"
></string-editor>
...
在另一种情况下(string-editor
替换为text-editor
)
<form>
<text-editor
[propertyName]="'code'"
[entity]="entity"
></text-editor>
...
依此类推(属性类型不同的编号/日期/引用编辑器
,跳过某些用户的某些属性...)。即这是一个示例,实际配置可以生成更多不同和复杂的模板。
模板正在更改,因此我无法使用componentfactoryresolver
并传递现有的...我需要一个使用编译器
的解决方案。
注意:要获取以前版本的解决方案,请查看此帖子的历史记录
这里讨论了类似的主题,相当于Angular 2中的$compile。我们需要使用jitcompiler
和ngmodule
。在此处阅读有关Angular2中NGModule
的更多信息:
有一个正在工作的柱塞/示例(动态模板、动态组件类型、动态模块、JITCompiler
、...in action)
其原则是:
1)创建模板
2)在缓存中查找ComponentFactory
-转到7)
3)创建Component
4)创建Module
5)编译Module
6)返回(并缓存供以后使用)ComponentFactory
7)使用目标和ComponentFactory
创建动态Component
实例
这里是一个代码片段(这里有更多内容)--我们的自定义构建器返回刚刚构建/缓存的ComponentFactory
和视图目标占位符consumer来创建DynamicComponent
的实例
// here we get a TEMPLATE with dynamic content === TODO
var template = this.templateBuilder.prepareTemplate(this.entity, useTextarea);
// 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;
//...
});
就是这样--简而言之。获取更多详细信息..阅读下面的内容
.
观察一个柱塞,如果某个片段需要更多的解释,就回来阅读详细信息
.
在此场景的描述下,我们将
partsmodule:ngmodule
(小块的持有者)DynamicModule:ngModule
,它将包含我们的动态组件(并动态引用PartsModule
)组件
类型(仅当模板已更改时)runtimemodule:ngmodule
。此模块将包含先前创建的组件
类型JITCompiler.CompileModuleAndallComponentsAsync(runtimeModule)
获取ComponentFactory
DynamicComponent
作业和ComponentFactory
@inputs
分配给新实例(从input
切换到textarea
编辑),使用@outputs
我们需要一个ngmodule
s。
虽然我想展示一个非常简单的例子,但在本例中,我需要三个模块(实际上是4个--但我不计算AppModule)。请把这个而不是一个简单的片段作为一个真正坚实的动态组件生成器的基础。
所有小组件都有一个模块,例如字符串编辑器
,文本编辑器
(日期编辑器
,数字编辑器
...)
@NgModule({
imports: [
CommonModule,
FormsModule
],
declarations: [
DYNAMIC_DIRECTIVES
],
exports: [
DYNAMIC_DIRECTIVES,
CommonModule,
FormsModule
]
})
export class PartsModule { }
其中dynamic_directives
是可扩展的,用于保存用于动态组件模板/类型的所有小部件。检查app/parts/parts.module.ts
第二个模块是动态处理的模块。它将包含托管组件和一些提供程序。这将是单身。因此,我们将以标准的方式发布它们--使用forroot()
import { DynamicDetail } from './detail.view';
import { DynamicTypeBuilder } from './type.builder';
import { DynamicTemplateBuilder } from './template.builder';
@NgModule({
imports: [ PartsModule ],
declarations: [ DynamicDetail ],
exports: [ DynamicDetail],
})
export class DynamicModule {
static forRoot()
{
return {
ngModule: DynamicModule,
providers: [ // singletons accross the whole app
DynamicTemplateBuilder,
DynamicTypeBuilder
],
};
}
}
检查AppModule
中forRoot()
的用法
最后,我们需要一个特殊的运行时模块…但它将在以后作为DynamicTypeBuilder
作业的一部分创建。
第四个模块,应用程序模块,是保存声明编译器提供程序的模块:
...
import { COMPILER_PROVIDERS } from '@angular/compiler';
import { AppComponent } from './app.component';
import { DynamicModule } from './dynamic/dynamic.module';
@NgModule({
imports: [
BrowserModule,
DynamicModule.forRoot() // singletons
],
declarations: [ AppComponent],
providers: [
COMPILER_PROVIDERS // this is an app singleton declaration
],
阅读(确实阅读)有关NgModule的更多信息:
在我们的示例中,我们将处理这类实体的细节
entity = {
code: "ABC123",
description: "A description of this Entity"
};
为了创建模板
,在这个plunker中,我们使用了这个简单/朴素的构建器。
真正的解决方案,一个真正的模板构建器,是应用程序可以做很多事情的地方
// plunker - app/dynamic/template.builder.ts
import {Injectable} from "@angular/core";
@Injectable()
export class DynamicTemplateBuilder {
public prepareTemplate(entity: any, useTextarea: boolean){
let properties = Object.keys(entity);
let template = "<form >";
let editorName = useTextarea
? "text-editor"
: "string-editor";
properties.forEach((propertyName) =>{
template += `
<${editorName}
[propertyName]="'${propertyName}'"
[entity]="entity"
></${editorName}>`;
});
return template + "</form>";
}
}
这里的一个技巧是-它构建一个模板,该模板使用一些已知属性集,例如entity
。这样的属性(-ies)必须是我们接下来要创建的动态组件的一部分。
为了让它更容易一点,我们可以使用一个接口来定义属性,我们的模板构建器可以使用它。这将由我们的动态组件类型实现。
export interface IHaveDynamicData {
public entity: any;
...
}
这里很重要的一点是要记住:
我们的组件类型(使用DynamicTypeBuilder
构建)可能有所不同--但只是因为它的模板(上面创建的)不同。组件的属性(输入、输出或某些受保护的)仍然相同。如果我们需要不同属性,我们应该定义不同的模板和类型生成器组合
所以,我们正在触及我们解决方案的核心。构建器将1)创建componenttype
2)创建其ngmodule
3)编译componentfactory
4)缓存它以供以后重用。
我们需要接收的依赖项:
// plunker - app/dynamic/type.builder.ts
import { JitCompiler } from '@angular/compiler';
@Injectable()
export class DynamicTypeBuilder {
// wee need Dynamic component builder
constructor(
protected compiler: JitCompiler
) {}
下面是如何获得componentFactory
的片段:
// plunker - app/dynamic/type.builder.ts
// this object is singleton - so we can use this as a cache
private _cacheOfFactories:
{[templateKey: string]: ComponentFactory<IHaveDynamicData>} = {};
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);
});
});
}
上面我们创建并缓存组件
和模块
。因为如果模板(实际上是所有的真正动态部分)是相同的…我们可以重复使用
这里有两个方法,它们代表了如何在运行时创建修饰的类/类型的非常酷的方法。不仅@component
而且@ngmodule
protected 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;
}
protected createComponentModule (componentType: any) {
@NgModule({
imports: [
PartsModule, // there are 'text-editor', 'string-editor'...
],
declarations: [
componentType
],
})
class RuntimeComponentModule
{
}
// a module for just this Type
return RuntimeComponentModule;
}
重要:
我们的组件动态类型不同,但只是模板不同。所以我们用这个事实来缓存它们。这真的非常重要。Angular2也将缓存这些..按类型。如果我们为相同的模板字符串重新创建新类型...我们将开始产生内存泄漏。
最后一块是一个组件,它承载动态组件的目标,例如。我们获得对它的引用,并使用
componentFactory
创建一个组件。这是一个简单的例子,这里是该组件的所有部分(如果需要,在这里打开柱塞)
我们先总结一下导入语句:
import {Component, ComponentRef,ViewChild,ViewContainerRef} from '@angular/core';
import {AfterViewInit,OnInit,OnDestroy,OnChanges,SimpleChange} from '@angular/core';
import { IHaveDynamicData, DynamicTypeBuilder } from './type.builder';
import { DynamicTemplateBuilder } from './template.builder';
@Component({
selector: 'dynamic-detail',
template: `
<div>
check/uncheck to use INPUT vs TEXTAREA:
<input type="checkbox" #val (click)="refreshContent(val.checked)" /><hr />
<div #dynamicContentPlaceHolder></div> <hr />
entity: <pre>{{entity | json}}</pre>
</div>
`,
})
export class DynamicDetail implements AfterViewInit, OnChanges, OnDestroy, OnInit
{
// wee need Dynamic component builder
constructor(
protected typeBuilder: DynamicTypeBuilder,
protected templateBuilder: DynamicTemplateBuilder
) {}
...
我们只是接收,模板和组件构建器。接下来是我们的示例所需的属性(更多信息请参阅注释)
// reference for a <div> with #dynamicContentPlaceHolder
@ViewChild('dynamicContentPlaceHolder', {read: ViewContainerRef})
protected dynamicComponentTarget: ViewContainerRef;
// this will be reference to dynamic content - to be able to destroy it
protected componentRef: ComponentRef<IHaveDynamicData>;
// until ngAfterViewInit, we cannot start (firstly) to process dynamic stuff
protected wasViewInitialized = false;
// example entity ... to be recieved from other app parts
// this is kind of candiate for @Input
protected entity = {
code: "ABC123",
description: "A description of this Entity"
};
在这个简单的场景中,我们的托管组件没有任何@input
。因此它不必对变化作出反应。但尽管如此(并且为即将到来的更改做好准备)--如果组件已经(首次)启动,我们需要引入一些标志。只有这样我们才能开始魔法。
最后,我们将使用我们的组件构建器,以及它刚刚编译/缓存的componentfacotry
。我们的目标占位符将被要求用该工厂实例化组件
。
protected refreshContent(useTextarea: boolean = false){
if (this.componentRef) {
this.componentRef.destroy();
}
// here we get a TEMPLATE with dynamic content === TODO
var template = this.templateBuilder.prepareTemplate(this.entity, useTextarea);
// 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;
//...
});
}
此外,我们需要保留一个对编译模板的引用…以便能够正确地destroy()
它,无论何时我们要更改它。
// this is the best moment where to start to process dynamic stuff
public ngAfterViewInit(): void
{
this.wasViewInitialized = true;
this.refreshContent();
}
// wasViewInitialized is an IMPORTANT switch
// when this component would have its own changing @Input()
// - then we have to wait till view is intialized - first OnChange is too soon
public ngOnChanges(changes: {[key: string]: SimpleChange}): void
{
if (this.wasViewInitialized) {
return;
}
this.refreshContent();
}
public ngOnDestroy(){
if (this.componentRef) {
this.componentRef.destroy();
this.componentRef = null;
}
}
差不多就是这样。不要忘记销毁任何动态构建的东西(ngOnDestroy)。此外,如果动态类型
和模块
的唯一区别是它们的模板,请确保缓存它们。
在这里检查所有的动作
要查看此文章的以前版本(例如RC5相关),请查看历史记录