gpt4 book ai didi

angular - 相当于 Angular 2 中的 $compile

转载 作者:行者123 更新时间:2023-11-28 05:29:55 25 4
gpt4 key购买 nike

我想手动编译一些包含指令的 HTML。 Angular 2 中的 $compile 相当于什么?

例如,在 Angular 1 中,我可以动态编译 HTML 片段并将其附加到 DOM:

var e = angular.element('<div directive></div>');
element.append(e);
$compile(e)($scope);

最佳答案

Angular 2.3.0 (2016-12-07)

要获取所有详细信息,请检查:

要查看实际效果:

主要内容:

1) 创建模板
2)创建组件
3)创建模块
4) 编译模块
5)创建(并缓存)ComponentFactory
6)使用Target创建它的实例

快速概述如何创建组件

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

一种将组件注入(inject)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;
}

如何创建 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);
});
});
}

如何使用上述结果的代码片段

  // 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;
//...
});

包含所有详细信息的完整描述 read here ,或观察working example

.

.

OBSOLETE - Angular 2.0 RC5 related (RC5 only)

to see previous solutions for previous RC versions, please, search through the history of this post

关于angular - 相当于 Angular 2 中的 $compile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39786691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com