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

72
Visualizações
Angular ngOnDestroy didn't fire

Demo

Demo fixed accordingly to accepted answer

Consider a component, let's call it <simple-dialog>, with this template:

<button type="button" (click)="visible = !visible">TOGGLE</button>
<div *ngIf="visible">
  <ng-content select="[main]"></ng-content>
</div>

I omit the component TypeScript definition cause it's basically the same as the one generated by ng-cli.

Then I use it like this:

  <simple-dialog>
    <div main>
      <app-form></app-form>
    </div>
  </simple-dialog>

When i first click the button the child component is rendered; if I click the button again the child component is removed from the DOM. The problem is that, at this point, app-form's ngOnDestroy is not called.

I'm new to angular, so I am not sure whether my expectation is wrong.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

What you are trying to achieve is called conditional content projection.

In your case, by using ng-content, the components are instantiated by the outer component, unconditionally - the inner component just decides not to display it.

If you want conditional instantiation, you should pass a template instead:

<simple-dialog>
  <ng-template>
    <div main>
      <app-form></app-form>
    </div>
  </ng-template>
</simple-dialog>

and use an @ContentChild annotated property to access the template from the content within the SimpleDialogComponent:

@ContentChild(TemplateRef, { static: false })
content!: TemplateRef<unknown>;

which can then be rendered in the template as

<div *ngIf="visible">
  <ng-container [ngTemplateOutlet]="content"></ng-container>
</div>

You can also read about this here: https://angular.io/guide/content-projection#conditional-content-projection

about 4 years ago · Santiago Trujillo 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