我想创建动态组件,之前当我使用Angular 2时,我使用了另一个堆栈溢出答案中的这段代码,该代码工作正常,直到我切换到Angular-cli。如何让它在角度cli中工作?
import {
Component,
Directive,
NgModule,
Input,
ViewContainerRef,
Compiler
} from '@angular/core';
import { CommonModule } from '@angular/common';
@Directive({
selector: 'html-outlet'
})
export class HtmlOutlet {
@Input() html: string;
constructor(private vcRef: ViewContainerRef, private compiler: Compiler) {}
ngOnChanges() {
const html = this.html;
if (!html) return;
@Component({
selector: 'dynamic-comp',
templateUrl: html
})
class DynamicHtmlComponent { };
@NgModule({
imports: [CommonModule],
declarations: [DynamicHtmlComponent]
})
class DynamicHtmlModule {}
this.compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
.then(factory => {
const compFactory = factory.componentFactories.find(x => x.componentType === DynamicHtmlComponent);
this.vcRef.clear();
const cmpRef = this.vcRef.createComponent(compFactory, 0);
});
}
}