Here's an Plunker Example with the ComponentFactoryResolver
Firstly you have to register your dynamic component TestPage
properly
app.module.ts
@NgModule({
declarations: [MainPage, TestPage],
entryComponents: [TestPage]
})
Alternative option
Declare dynamic-module.ts
import { NgModule, ANALYZE_FOR_ENTRY_COMPONENTS } from '@angular/core';
@NgModule({})
export class DynamicModule {
static withComponents(components: any[]) {
return {
ngModule: DynamicModule,
providers: [
{
provide: ANALYZE_FOR_ENTRY_COMPONENTS,
useValue: components,
multi: true
}
]
}
}
}
and import it in app.module.ts
@NgModule({
imports: [ BrowserModule, DynamicModule.withComponents([TestPage]) ],
declarations: [ MainComponent, TestPage ]
})
Then your MainPage
component might look as follows:
import { ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
@Component({
selector: 'main-component',
template: `
<button (click)="putInMyHtml()">Insert component</button>
<p>stuff</p>
<div>
<template #target></template>
</div>
`
})
export class MainPage {
@ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef;
constructor(private cfr: ComponentFactoryResolver) {}
putInMyHtml() {
this.target.clear();
let compFactory = this.cfr.resolveComponentFactory(TestPage);
this.target.createComponent(compFactory);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…