Angular Create Component within Component
December 20, 2021 · 2 min readLucian CiobanuThe customer we're working for gave us the most challenging technical requirement towards the end of this year: we can have an infinite number of compoments nested within the parent component and clicking on a parent will show the related details.
First thing we did was to add a templat refference to the html as such:
component.component.html
<ng-template #host></ng-template>
In the component.component.ts, we use ViewChild to read teh ViewContainerRef and we can use an @Input to receive various data and we use ComponentFactoryResolver to create new components
[...]
export class ComponentComponent {
@ViewChild('host', {read: ViewContainerRef}) host: ViewContainerRef;
constructor(
private resolver: CopmonentFactoryResolver
) { }
//we will create a new component when needed as such:
private createNewLevel(newInstanceData) {
let componentRef: ComponentRef<ComponentComponent>;
const factory: ComponentFactory<ComponentComponent> = this.resolver.resolveComponentFactory(ComponentComponent);
componentRef = this.host.createComponent(factory)
componentRef.instance.dataComponents = {
Data1: newInstanceData.Data1ComponentChildren,
Data2: newInstanceData.Data2ComponentChildren
};
}
The code above is what's needed to create a new component and feed it the expected data as long as the component we create is the one we are actually working in a give the component the specified inputs. We've also used a state service to save an access general information regarding the created component.
Hope this helped!
Cheers,
Lucian

Web Development & Software Delivery