To dynamically add components, utilize the ComponentFactoryResolver
. Detailed information can be found in the Angular Docs. Check out a complete solution on stackblitz:
ComponentFactoryResolver. Here's a summary of what was implemented:
For table creation in app.component.ts
:
createTable(container) {
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(TableComponent);
let viewContainerRef = this.insTable.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
}
The anchor point directive used: table.directive.ts
:
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[ins-table]',
})
export class TableDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
In app.component.html
:
<div #charts id="test">
<ng-template ins-table></ng-template>
</div>
Also, don't forget to set up app.module.ts
with the necessary declarations for everything to function correctly:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ChartModule } from 'angular-highcharts';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { TableComponent } from './table/table.component';
import { TableDirective } from './table/table.directive';
@NgModule({
imports: [BrowserModule, ChartModule, HttpClientModule],
declarations: [AppComponent, TableComponent, TableDirective],
bootstrap: [AppComponent],
providers: [HttpClientModule],
entryComponents: [
TableComponent
]
})
export class AppModule { }