如何解决如何在Angular 9中将ViewContainerRef与工厂的动态组件一起使用?
此问题直接与公共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 isssue with dynamic component load
我希望发布会允许人们分享一些想法,或者向我指出出现问题的正确方向,或者甚至可以在Angular 9 Ivy编译器中做到这一点?任何帮助都非常感谢!
解决方法
我做了一些挖掘,弄清楚了我的问题。 lView
在我的参考资料中不存在,因为我在tsconfig中关闭了Ivy的情况下编译了该组件/模块,但在那个环境中却没有加载该文件/模块:
"angularCompilerOptions": {
"enableIvy": false
}
现在,在我也动态加载这些组件的环境中关闭Ivy时,它会按预期工作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。