Solvedangular Nested Dynamic Components Break With ComponentFactoryResolver

I'm submitting a ... (check one with "x")

[ x ] bug report => search github for a similar issue or PR before submitting
[ ] feature request
[ ] support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior
When trying to render nested dynamic components via the ComponentFactoryResolver I receive an exception/error message:

browser_adapter.js:84Error: Expression has changed after it was checked. Previous value: 'CD_INIT_VALUE'. Current value: 'null'. It seems like the view has been created after its parent and its children have been dirty checked. Has it been created in a change detection hook ?

Expected/desired behavior

It should render the nested dynamic controls. This had worked until the introduction of the ComponentFactoryResolver. See: https://plnkr.co/edit/JRyqou9yC6LvSRrCR3eA?p=preview

Reproduction of the problem

Here is the plunkr recreating the issue: http://plnkr.co/edit/NzT4a7GEAB7k4yqeZrs0?p=preview

What is the expected behavior?

I should be able to render a control via ComponentFactoryResolver which in turn also renders multiple controls via ComponentFactoryResolver.

In my use case, I am rendering a form wizard made up of several dynamic components. In one of those dynamic components I am pulling fields defined in the database to render a set of user controlled fields.

What is the motivation / use case for changing the behavior?

It used to work.

Please tell us about your environment:

  • Angular version: 2.0.0-rc.5
  • Browser: [all ]
  • Language: [all ]
13 Answers

✔️Accepted Answer

For anyone looking for a dirty hack, wrap your code in a setTimeout():

public ngAfterViewInit(): any {
    setTimeout(() => {
        let modalFactory = this.componentResolver.resolveComponentFactory(<any>this.modalInstance.config.content);
        this.componentInstance = this.container.createComponent(modalFactory, null, this.injector);
    }, 1);
}

Other Answers:

Use the "AfterContentInit" lifecycle-hook to init/update your nested dynamic-component.

public ngAfterContentInit() {
  let modalFactory = this.componentResolver.resolveComponentFactory(<any>this.modalInstance.config.content);
  this.componentInstance = this.container.createComponent(modalFactory, null, this.injector);
}

updated your plunker:
http://plnkr.co/edit/EasYKceQTBC9yA4Xsma8?p=preview

More Issues: