Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
How to replace component in ViewContainerRef in Angular?

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:

  1. To create a firstComponent and save reference to it (I can do it)
  2. To create the secondComponent in the place of the first one. I remove the firstComponent and create the secondComponent (I can do it).
  3. To remove the secondComponent and again insert the saved firstComponent. It is very important - not to create a new instance of the firstComponent, 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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use detach() and insert() methods for such purpose. According to the documentation:

Detaches a view from this container without destroying it. Use along with insert() to move a view within the current container.

const firstComponent = this.container.createComponent<FirstComponent>(FirstComponent);

// detach without destroying
this.container.detach(0);

// insert the firstComponent with preserved elements.
this.container.insert(firstComponent.hostView, 0);

about 4 years ago · Juan Pablo Isaza Relatório

0

I would go with something like this

if(this.container && this.container.length>0){
    // if you do not know the index, search it first and than detach it
    this.container.detach(this.container.indexOf(firstComponent));
} 
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda