这个问题与公共 Angular API 直接相关:https ://angular.io/api/core/ViewContainerRef#insert
我通过这段代码从他们的 ngFactories 动态加载组件。
我已经从 Angular 8.2 升级到 9.1,并且在我的组件加载到视图中的方式中发现了一些错误。在升级到 Angular 9.1 之前,这段代码运行良好:
// Create a view for the component to be inserted into
@ViewChild('myView', { read: ViewContainerRef, static: true }) myView: ViewContainerRef;
// Grab dynamic module
let moduleFactory: NgModuleFactory<any> = myNgFactory;
// Create reference using the current code's injector
let moduleReference = moduleFactory.create(this.injector);
// Grab the component factory from the module
let componentFactory = moduleReference.componentFactoryResolver.resolveComponentFactory(myComponentFactory);
// Create the component
let component = componentFactory.create(moduleReference.injector);
// Then insert into myView
this.myView.insert(component.hostView);
尝试运行时,错误发生在最后一行ViewContainerRef.insert
错误:
ERROR TypeError: Cannot read property '1' of undefined
at ViewContainerRef.insert(core.js:15711)
...
错误发生在控制台(编译核心)中:
insert(viewRef, index) {
/** @type {?} */
const lView = (/** @type {?} */(((/** @type {?} */(viewRef)))._lView));
const tView = lView[TVIEW];
^^^^^^^^
...
}
我在 core.js 文件中发现更高的const TVIEW = 1
直接的 Angular 代码参考(据我所知,代码没有从 Angular 8 更改为 9): https ://github.com/angular/angular/blob/9.1.x/packages/core/src/view/refs .ts#L207
我试图插入的我的 Component 对象(我确实看到了组件的细微差别,这是原因吗?):
我发现了一个类似的问题,但我收到了一个不同的错误:Angular 9 issue with dynamic component load
我希望发帖可以让人们分享一些想法,或者指出我在哪里出了问题,或者这在 Angular 9 Ivy 编译器中是否可行?对此的任何帮助都非常感谢!