3

I'm trying to load a component dynamically using the ComponentResolver and ViewContainerRef services.

The child component loads ok and the template is rendered. However i want to access the inputs from the parent ('field' and 'values') inside the child component.

Any help would be much appreciated.

Parent component:

import {Component, Input, ViewChild, ComponentFactory, ViewContainerRef, ComponentResolver} from '@angular/core';
import {MyInputComponent} from './my-input.component';

@Component({
    selector: 'my-field',
    template: `
        <label class="control-label">
            <span>{{field.label}}</span>
            <span class="required">*</span>
        </label>
        <div #target></div>
    `
})
export class MyFieldComponent {

    @Input() field;
    @Input() values;

    @ViewChild('target', { read: ViewContainerRef }) target;

    ngAfterViewInit() {
        this.compiler.resolveComponent(MyInputComponent).then((factory: ComponentFactory<any>) => {
            this.target.createComponent(factory);
        });
    }

    constructor(public viewContainerRef: ViewContainerRef, private compiler: ComponentResolver) {
    }

}

Child component:

import {Component, Input, ViewContainerRef} from '@angular/core';

@Component({
    selector: 'my-input',
    template: `
        This is an input component!!!
    `
})
export class MyInputComponent {

    @Input() field: any;
    @Input() values: any;


    ngOnInit() {
        console.log(this);
    }

    constructor(public viewContainerRef: ViewContainerRef) {
    }

}

1 Answer 1

4

I think that you can leverage something like this:

this.compiler.resolveComponent(MyInputComponent).then((factory: ComponentFactory<any>) => {
   let component = this.target.createComponent(factory);
   component.instance.field = this.field;
});

See also the example https://plnkr.co/edit/bdGYvTf8y9LEw9DAMyN1?p=preview

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, worked perfectly. I've been trying to get my head around the ComponentResolver now that DynamicComponentLoader has been deprecated.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.