gpt4 book ai didi

angular - 等价于 Angular 2 中的 $compile

转载 作者:太空狗 更新时间:2023-10-29 19:34:59 26 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/41508258/

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