Angular 动态创建的组件未维护其状态

Angular Dynamically created component are not maintaining their state

我正在尝试动态创建多个组件,这些组件将放置在 table 中。当前的代码实现了这个目标,但是状态似乎在动态创建的组件级别变得混乱。因此,当单击一个组件时,我们查看单击处理程序内部,在动态生成的组件中,this.data 显示最后一个动态生成的组件的数据(如果 3 个组件创建状态将始终引用预期的内容组件 #3,无论单击哪个组件)。请记住,渲染时显示的数据是正确的,只有在单击组件进行排序时,事情才会变得奇怪。如果在任何给定时间只有一个动态创建的组件显示在 Dom 上,这当然不是问题。

有没有想过 why/how 动态生成的组件的状态变得一团糟?我已经阅读了很多关于该主题的帖子,但没有发现 across/address 这个问题。

@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;
    }

我得出的结论是,我在 TableCellComponent 级别通过 this.componentRef.instance.data = tableCellItem.data 将对“this”的引用向下传递到我的 ngOnInit 中的新创建的组件。因此,每次 TableCellComponent 中的“this”发生变化时,它也会在我动态创建的组件中发生变化,并随之破坏我呈现的内容(因此所有组件都被正确呈现)与作为“this”访问的内容之间的关系在我的点击处理程序中。

为了解决这个问题,我不得不将我的数据深度复制到动态创建的组件中。

this.componentRef.instance.data = tableCellItem.data;

改为

this.componentRef.instance.data = {...tableCellItem.data};

是一个简单的修复!