【问题标题】:Angular Dynamically created component are not maintaining their stateAngular 动态创建的组件未保持其状态
【发布时间】:2021-09-15 17:21:40
【问题描述】:

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

对于动态生成的组件的状态为何/如何变得混乱有任何想法吗?我已阅读有关该主题的大量帖子,但没有发现任何遇到/解决此问题的帖子。

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

【问题讨论】:

    标签: angular typescript dynamic components state


    【解决方案1】:

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

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

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

    改为

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

    是一个简单的解决方法!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-02
      • 1970-01-01
      • 2020-02-26
      • 2012-03-09
      • 2019-12-08
      • 2017-02-24
      相关资源
      最近更新 更多