Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

69
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!