Например так:
import {
Component,
ViewChild,
ViewContainerRef,
OnInit,
ComponentFactoryResolver,
Injector,
EmbeddedViewRef,
ElementRef
} from '@angular/core'
import { Type } from '@angular/core'
@Component({
selector: 'app-root',
template: '<h1>Скомпилируй</h1> <div #outlet></div>',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
public title = 'app'
public AnyComponent
@ViewChild('outlet') outlet: ElementRef
constructor(
private readonly factoryResolver: ComponentFactoryResolver,
private readonly injector: Injector
) {}
public ngOnInit() {
this.appendComponent(this.AnyComponent)
}
public appendComponent<T>(component: Type<T>) {
const componentRef = this.factoryResolver
.resolveComponentFactory(component)
.create(this.injector)
const domElem = (componentRef.hostView as EmbeddedViewRef<any>)
.rootNodes[0] as HTMLElement
this.outlet.nativeElement.appendChild(domElem)
}
}