What you are trying to do is creating components programmatically and then access their methods and properties.
The way Angular works for creating an instance of a component is using a Factory resolver which will create the new component, and a ViewContainerRef where the component will be attached and rendered.
First create a directive which will serve as the ViewContainerRef for one of your tables, which will render the component (what I believe you are missing right now) and allow you to access its methods and properties.
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appTable]'
})
export class TableDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
Now you can add it to a ng-template tag and render a component inside using the FactoryResolver:
import { Component, ComponentFactoryResolver, ViewChild, OnInit, ComponentRef } from '@angular/core';
import { TableComponent } from './table/table.component';
import { TableDirective } from './table.directive';
@Component({
selector: 'app-root',
template: `
<ng-template appTable></ng-template>
`,
})
export class AppComponent implements OnInit {
@ViewChild(TableDirective) tableHost: TableDirective;
tableComponent: ComponentRef<TableComponent>;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
}
ngOnInit() {
// TableComponents = new TableComponents(); wrong way!
/**
* creating the component factory resolver
*/
const tableFactory = this.componentFactoryResolver.resolveComponentFactory(TableComponent);
const viewContainerRef = this.tableHost.viewContainerRef;
/**
* clearing just in case something else was rendered before
*/
viewContainerRef.clear();
/**
* now you will be able to access the methods and properties of your component after this
*/
this.tableComponent = viewContainerRef.createComponent(tableFactory);
}
}
Finally as the component is being rendered programmatically you need to add it in the entryComponents array in you module:
@NgModule({
declarations: [
AppComponent,
TableComponent,
TableDirective
],
imports: [
BrowserModule
],
entryComponents: [TableComponent],
providers: [],
bootstrap: [AppComponent]
})
I made a demo so it's more clear, you can read more about creating components dynamically in this article by Luka Onikadze.