typescript 动态编译HTML的指令。来源:https://plnkr.co/edit/mcvILwmOLvrS2PxIrXX8?p = preview
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript 动态编译HTML的指令。来源:https://plnkr.co/edit/mcvILwmOLvrS2PxIrXX8?p = preview相关的知识,希望对你有一定的参考价值。
import {
Component,
Directive,
NgModule,
Input,
ViewContainerRef,
Compiler,
ComponentFactory,
ModuleWithComponentFactories,
ComponentRef,
ReflectiveInjector
} from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> {
const cmpClass = class DynamicComponent {};
const decoratedCmp = Component(metadata)(cmpClass);
@NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp] })
class DynamicHtmlModule { }
return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
.then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
return moduleWithComponentFactory.componentFactories
.find(x => x.componentType === decoratedCmp);
});
}
@Directive({
selector: 'client-html-outlet',
})
export class ClientHtmlOutletDirective {
@Input() html: string;
cmpRef: ComponentRef<any>;
constructor(private vcRef: ViewContainerRef, private compiler: Compiler) { }
ngOnChanges() {
const html = this.html;
if (!html) return;
if (this.cmpRef) {
this.cmpRef.destroy();
}
const compMetadata = new Component({
selector: 'dynamic-html',
template: this.html,
});
createComponentFactory(this.compiler, compMetadata).then(factory => {
const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
this.cmpRef = this.vcRef.createComponent(factory, 0, injector, []);
});
}
ngOnDestroy() {
if (this.cmpRef) {
this.cmpRef.destroy();
}
}
}
以上是关于typescript 动态编译HTML的指令。来源:https://plnkr.co/edit/mcvILwmOLvrS2PxIrXX8?p = preview的主要内容,如果未能解决你的问题,请参考以下文章
TypeScript中的指令,编译(前/后)的等价物是啥?
AngularJS 指令在使用 $.get 加载动态内容后编译
TypeScript教程# 5:TS编译选项
typescript基础语法
等到加载 HTML5 视频-Typescript
TypeScript入门八:TypeScript的命名空间