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;
That's expected behavior. You can invoke change detection explicitely though
componentRef.changeDetectorRef.detectChanges();
If you run change detection manually be aware that it will run for the component and all it children, means the full branch. So you need to think of detaching other children when creating new one.
This issue is tracked in: https://github.com/angular/angular/issues/22010