5

Say I have a dynamic-component-wrapper that can instantiate any Component class that is passed into it.

// DRE013 DCOOKE 16/05/2017 - The component to instantiate.
@Input() componentType: Type<{}>;

// DRE013 DCOOKE 16/05/2017 - the component that will be created
private _cmpRef: ComponentRef<Component>;


// DRE013 DCOOKE 16/05/2017 - Creates a component ref in the view at #target
createComponent(){

    let factory = this.componentFactoryResolver.resolveComponentFactory(this.componentType);
    this._cmpRef = this.target.createComponent(factory);
    //this._cmpRef.instance.inputs >>>>>>>>> this is a string[] and I do not see how I can use this 
}

Example usage

<shared-dynamic-component [componentType]="TestComponent"></shared-dynamic-component>

Where TestComponent = TestComponent //class

This works as expected, and I can receive an instance of this component from within the dynamic-component-wrapper like so:

this._cmpRef.instance

The Angular docs are not clear on this instance object - simply stating that instance is of type C - with absolutely no reference to what C actually is.

Thankfully my IDE was able to tell me that :

ComponentRef.instance has the following properties:

  • inputs : string[]
  • outputs : string[]

However I do not understand how I am meant to use this information. I'd imagine this is just the names of the @Input fields - but I cannot think how I can pass in a complex object as an Input.

Question

Is it possible for me to set the @Inputs and other meta-data after dynamically creating a component with the componentFactoryResolver?

3
  • C is a generic type parameter, because T was used elsewhere in this class I guess.
    – Supamiu
    May 18, 2017 at 13:48
  • Is it possible for me to set the @Inputs - do you want them to be updated automatically by Angular? May 18, 2017 at 14:00
  • @Maximus that would be ideal - It sounds a tad far-fetched I know. May 18, 2017 at 14:04

2 Answers 2

6

Automatic update

This doesn't seem to be possible. Here is the explanation why.

For each component, Angular compiler creates a factory. You can observe all factories in the sources tab under ng:// folder, here is the example of how it looks. When it creates a factory, it defines nodes that will be rendered inside this component view. Some of the nodes are child components.

And it is at the time of generating this factory it is defined which input properties the framework should track. So unless you defined input properties before the compilation, Angular will not be tracking and updating the inputs.

Here is an example of how this factory looks like:

function View_AppComponent_0(l) {
  return jit_viewDef2(0,[
    jit_queryDef3(201326592,1,{someComp: 0}),
    (l()(),jit_elementDef4(0,null,null,1,'h1',[],null,null,null,null,null)),
    (l()(),jit_textDef5(null,[
      'Hello ',
      ''
    ]
    )),
    (l()(),jit_textDef5(null,['\n\n'])),
    (l()(),jit_elementDef4(0,null,null,1,'b-comp',[],null,null,null,jit_View_BComponent_06,jit__object_Object_7)),

      *************************************
      // this is a child component's node definition which has `some` property binding
      jit_directiveDef8(24576,null,0,jit_BComponent9,[],{some: [
        0,
        'some'  <------------------------ property name to track
      ]
    },null)
     **************************************************

  ]

When you use this.componentFactoryResolver.resolveComponentFactory, it actually searches for that factory. It doesn't compile anything.

Manual update

This certainly possible. You can query a child component from the parent component and update the property - it will be correctly rendered in the child component's template. And you can even trigger onChanges lifecycle hook.

export class AppComponent {
  @ViewChild(BComponent) bc;

  ngAfterViewInit() {
    setTimeout(() => {
      this.bc.some = 'foo';
      const changes = {some: new SimpleChange('', 'foo', true)};
      this.bc.ngOnChanges(changes);
    })
  }
9
  • Some great information here +1 . This is kind of what I assumed anyway. Will accept this as an answer if no one else can chime in. May 18, 2017 at 14:26
  • 1
    @DanielCooke, sure, I've added some information regarding manual update. Also, you might find interesting all Angular articles on my blog, they are quite informative and in-depth May 18, 2017 at 14:39
  • brilliant - followed your blog. This is exactly the kind of resource I've been looking for. May 18, 2017 at 14:42
  • I'm having a similar problem. However, my dynamic component has two inputs. One of which receives the passed in parameter, as explained above. The other does not, even though I pass it the same way in the next statement. The working input is a "number" while the failing one is a "string", I doubt this is the problem. Using console.log at the time the values are set, indicates the failing input is correctly set. But console.log inside the target component returns undefined.
    – Zarepheth
    Nov 2, 2017 at 16:29
  • 1
    @MaxWizardK, it works now, i had a bug elsewhere. Thanks ;)
    – aguetat
    Oct 11, 2018 at 9:49
3

I ended up creating a class to do so... incase this helps anyone else.

Usage

const componentChangeBuilder = new DynamicComponentChangeBuilder(componentRef);
componentChangeBuilder.addInput('inputName', 'some string value');
componentChangeBuilder.addInput('someOtherInputName', 1234);
componentChangeBuilder.commit();

import { ComponentRef, OnChanges, SimpleChange, SimpleChanges } from '@angular/core';

/**
 * Use this to track and trigger ngOnChanges for dynamically loaded components.
 */
export class DynamicComponentChangeBuilder<TComponent = any> {
    private readonly componentRef: ComponentRef<TComponent>; 
    private readonly inputs = new Map<keyof TComponent, TComponent[keyof TComponent]>();
    private readonly changesHistory = {} as SimpleChanges;

    constructor(componentRef: ComponentRef<TComponent>) {
        this.componentRef = componentRef;        
    }

    public addInput(
        input: keyof TComponent,
        value: TComponent[typeof input],
    ): void {
        this.inputs.set(input, value);
    }

    public commit() {
        const currentChanges = {} as SimpleChanges;

        this.inputs.forEach((newValue, input) => {
            const previousChange = this.changesHistory[input as string];
            let currentChange: SimpleChange;
            if (!!previousChange) {
                currentChange = {
                    previousValue: previousChange.currentValue,
                    currentValue: newValue,
                    firstChange: false,
                } as SimpleChange;
            } else {
                currentChange = {
                    currentValue: newValue,
                    firstChange: true,
                } as SimpleChange;
            }

            this.changesHistory[input as string] = currentChange;
            currentChanges[input as string] = currentChange;
            this.componentRef.instance[input] = currentChange.currentValue;
        });

        if (implementsOnChanges(this.componentRef.instance)) {
            this.componentRef.instance.ngOnChanges(currentChanges);
        }
    }
}

function implementsOnChanges(component: any): component is OnChanges {
    return (component as OnChanges)?.ngOnChanges !== undefined;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.