2

I have the following code to load a module dynamically:

export class DynamicQuestionComponent {
    constructor(
        private componentFactoryResolver: ComponentFactoryResolver,
        private viewContainerRef: ViewContainerRef
    ) {}

    @Input() form: FormBase;
    @Input() formgroup: FormGroup;
    @ViewChild('content', { read: ViewContainerRef, static: true }) content: ViewContainerRef;

    @Input() set question(qvalue){
        if (qvalue){
            this.content.clear();
            var compath = `./${qvalue.qType}-question.component`;
            var testpath = './proto-question.component';
            import('./proto-question.component').then( dyncomp => {
                const component = this.viewContainerRef.createComponent(this.componentFactoryResolver.resolveComponentFactory(dyncomp.ProtoQuestionComponent));
                (<any>component).instance.form = this.form;
                (<any>component).instance.question = qvalue;
                (<any>component).instance.formgroup = this.formgroup;
                this.content.insert(component.hostView);
                component.injector.get(ChangeDetectorRef).markForCheck();
            })
        }
    }
}

Currently, this is the only way it works, if I hard code the component path inside of the import function. I want to be able to pass a variable into the import function, but each time I switch to the variable, I get the dreaded cannot find module error:

ERROR Error: Uncaught (in promise): Error: Cannot find module './proto-question.component'

As you can see, I even tested a variable that is exactly the same as the hardcoded version and that fails as well.

I feel like there must be a setting to make this work properly.

I"m using:

Angular 9.1.9

Angular CLI 9.1.4

Assuming I can get past the dynamic variable issue, then I need to figure out how to get pass in the dynamic component into the resolveComponentFactory call.

0

1 Answer 1

0

Unfortunately loading a dynamic module by variable is not possible. I have similar issue and i can't find a solution. Dynamically import modules with dynamic routes

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

1 Comment

I think I have come to this conclusion as well, sigh.

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.