首页 > 解决方案 > 在 Angular 中动态加载组件

问题描述

我目前正在开发一个应用程序,它使用角垫表显示一个表格。我希望动态添加每个单元格的内容。所以在我的 html 代码中,我在单元格区域中添加了一个锚元素。一般来说,我一直遵循文档中的描述(https://angular.io/guide/dynamic-component-loader)。只是,因为我有多个模板,所以我使用的是 ViewChildren 而不是 ViewChild。所以我必须订阅 ViewChildren 的查询列表,以便在添加后得到通知。初始化列表后,我想动态加载我实际想要的组件。如https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4中所述这会导致 ExpressionChangedAfterItHasBeenCheckedErrorerror,因为我在订阅调用中更明确地将组件加载到 on change 挂钩中。我可以使用文章中描述的解决方法来解决这个问题,比如调用detectChanges(),但这并不能解决一般设置的问题,这让我感觉不对。有没有预期的方法来处理这个问题?我用我想要实现的简化版本创建了这个 stackblitz https://stackblitz.com/edit/angular-gitter-mc3xdi。它的构建类似于文档https://stackblitz.com/angular/eaaeaqnnaqxg的示例

标签: angularangular-dynamic-components

解决方案


推荐阅读