Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

68
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda