I am learning Angular and I need to create components dynamically and swap them in one container. I have a container:
<ng-container #container></ng-container>
And I need to do these steps:
- To create a
firstComponentand save reference to it (I can do it) - To create the
secondComponentin the place of the first one. I remove thefirstComponentand create thesecondComponent(I can do it). - To remove the
secondComponentand again insert the savedfirstComponent. It is very important - not to create a new instance of thefirstComponent, but insert the saved one. And this is what I can't do.
This the code I use to create components dynamically (angular 13):
@ViewChild("container", { static: true, read: ViewContainerRef })
container!: ViewContainerRef;
...
const firstComponent = this.container.createComponent<FirstComponent>(FirstComponent);
...
//to remove it I do
this.container.remove(0);
Could anyone say how to do step #3?