Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change detection not working when creating a component via 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;

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;
like image 608
Jus10 Avatar asked Mar 30 '17 08:03

Jus10


1 Answers

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

componentRef.changeDetectorRef.detectChanges();
like image 73
Günter Zöchbauer Avatar answered Oct 22 '22 05:10

Günter Zöchbauer