In creating dynamic components in Angular 2, I found out that this process requires ViewContainerRef
in order to add newly created component to DOM.
And in passing @Input
and @Output
to those dynamically created components, I found the answer in the second link above and here.
However, if I were to create a service named shape.service
that contains functions returning different shape components with some @Input
like bgColor
, I don't know how this service will create a component without specifying DOM location, and how the container-component receives this returned component (probably its type will be ComponentRef
) from the service and injects it to the DOM container-component specifies.
For example, a service contains a method:
getCircle(bgColor:string): ComponentRef<Circle> {
let circleFactory = componentFactoryResolver.resolveComponentFactory(CircleComponent);
let circleCompRef = this.viewContainerRef.createComponent(circleFactory);
circleCompRef.instance.bgColor = bgColor;
return circleCompRef;
}
First question rises here, how do I make this.viewContainerRef
point to no where for the meantime? The reason why I'm importing ViewContainerRef
is to create component dynamically.
Second question is after container-component receives input-specificcomponentRef
from the service, how will it inject to its DOM?
UPDATE: I think my question above wasn't specific enough. I'm in a situation where:
- A parent component calls the service and gets the componentRef/s,
- Creates an object including componentRef/s together with some other data and stores those created object/s into array
- Passes it to its children as
@Input
, - And let each child inject componentRef to its DOM and use rest of the data in the object in other way.
That means the service calling component has no idea where those componentRef will get injected. In short, I need independent component objects that can be injected to anywhere, anytime I want.
I'm reading the rumTimeCompiler solution several times already but I don't really get how that really works. It seems like there's too much work compared to component creation using viewContainerRef. I'll dig into that more if I find no other solution...