通过 ComponentFactoryResolver 创建组件时更改检测不起作用

编程入门 行业动态 更新时间:2024-10-28 03:21:27
本文介绍了通过 ComponentFactoryResolver 创建组件时更改检测不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个组件,使用 ComponentFactoryResolver 创建另一个组件.似乎工作正常,我可以通过@Input 访问数据.问题是 ngOnChanges 在组件启动或数据更改时永远不会被调用.但是,如果我使用 HTML 中的选择器以正常方式创建组件,它确实会触发.但这不是动态的,所以我只剩下 ComponentFactoryResolver.这是正常行为吗?

I have a component, creating another component with ComponentFactoryResolver. It seems to work fine, I can access data through the @Input. Problem is ngOnChanges never gets called when the component boots up, or when the data changes. However, it does trigger if I create the component the normal way, with it's selector in HTML. That isn't dynamic though, so I am left with ComponentFactoryResolver. Is this normal behavior?

我的父组件有它的输入:

My parent component has it's input:

@ViewChild( MyDirective ) myHost: MyDirective;

@ViewChild( MyDirective ) myHost: MyDirective;

然后它创建子组件,其输入是这样的:

Then it creates child components whose inputs are like this:

@Input('key') key: String;
@Input('index') index: number;

我正在创建这样的组件:

and I'm creating the component like this:

let item = new Item(ItemDropdownComponent, this.key, 0);
let componentFactory = this._componentFactoryResolver.resolveComponentFactory(itemponent);
let viewContainerRef = this.myHost.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
(<ItemInterfaceComponent>componentRef.instance).key = item.key;
(<ItemInterfaceComponent>componentRef.instance).index = item.index;

推荐答案

这是预期的行为.您可以显式调用更改检测

That's expected behavior. You can invoke change detection explicitely though

componentRef.changeDetectorRef.detectChanges();

这篇关于通过 ComponentFactoryResolver 创建组件时更改检测不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-22 23:01:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1031305.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件   不起作用   ComponentFactoryResolver

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!