I’m trying to dynamically create multiple components which will be placed in a table. The current code achieves this goal, however state seems to get messed up at the dynamically created component level. So when a component is clicked and we look inside the click handler, within the dynamically generated component, this.data shows the data of the last dynamically generated component (if 3 components created state will always refer to what is expected to be in component #3 regardless of which component is clicked). Please keep in mind that data being displayed upon rendering is correct, things only get weird when the component is clicked for sorting purposes. This is of course a non issue if only one dynamically created component is showing on the Dom at any given time.
Any thoughts as to why/how state of the dynamically generated components are getting messed up? I've read numerous posts around the topic and have not found any that comes across/address this issue.
@Component({
selector: 'table-cell',
template: '<ng-template tableCellHost></ng-template>'
})
export class TableCellComponent implements OnInit, OnDestroy, AfterViewInit {
@Input() tableData: any[];
@ViewChild(TableCellDirective, { static: true }) tableCellHost: TableCellDirective;
public componentRef: any;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
ngOnInit(): void {
const tableCellItem = new TableCellItem(this.data.component, this.data);
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(tableCellItem.component);
const viewContainerRef = this.tableCellHost.viewContainerRef;
viewContainerRef.clear();
this.componentRef = viewContainerRef.createComponent<TableCellInterface>(componentFactory);
this.componentRef.instance.data = tableCellItem.data;
}
ngAfterViewInit() {
this.componentRef.instance.data.tableData = this.tableData;
}