通过ComponentFactoryResolver创建组件时,更改检测不起作用 [英] Change detection not working when creating a component via ComponentFactoryResolver
问题描述
我有一个组件,使用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?
我的父级组件已输入:
@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(item.component);
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屋!