问题描述
限时送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:关键词]
发布评论