3

I am trying to build a dynamic component inside any container. I needed some predefined services and injections available in the angular world inside the dynamically created component. Primary reason for this there is an external service that holds the responsibility of look of the component but Additional actions needs be performed on component in the client side.

private elementRef: ElementRef in the constructor of dynamic component for injection causes problem and it unable to provide values for injection. Getting the error - "ERROR Error: Can't resolve all parameters for Xyz: (?)."

const component = Component({
            template: div,
            selector: 'test'
        })(
            class Xyz {
                constructor(private elementRef: ElementRef) { }
            });
        const module = NgModule({ declarations: [component] })(class {
        });
        this.compiler.compileModuleAndAllComponentsAsync(module)
            .then((factories) => {
                const f = factories.componentFactories[0];
                const cmpRef = f.create(this.injector, [], null, this.ngModuleRef);
                                container.clear();
                container.insert(cmpRef.hostView);
             });

What is the best way to inject or pass parameters to a constructor that is dynamically created?

2
  • Umm, not to kill your vibe or anything, but there is a library to simplify the dynamic component control @angular/cdk, @angular/material is built on top of it, and the utilities might be really useful. Commented Oct 16, 2019 at 13:43
  • I have used CDK and it actually doesn't work for my use case, material is more for the design and doesn't help with the construction itself. Assume that I have a div element coming from an external source that I want to render at runtime how exactly can these libraries help? Commented Oct 17, 2019 at 8:01

1 Answer 1

1

It works if you define Component and NgModule as @Component and @NgModule syntax. I had the same problem when using the approach you used. I don't know the exact reason why one doesn't work and the other does. Check this accepted answer: How to access the function when using dynamic injecting component in Angular

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.