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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With