⊗jsagPmLCOD 72 of 97 menu

The ngOnDestroy hook in Angular

The ngOnDestroy hook is triggered when a component is destroyed. In this hook, you can free resources, remove subscriptions to element events, leave timers, etc.

Creating and removing a component in Angular happens when it is reactively shown and hidden using the if condition. That is, Angular does not just hide components, it removes them and brings them back.

Also, components are created and destroyed when they are reactively iterated in loops. In this case, Angular also creates and destroys components.

Let's try it in practice. We import the OnDestroy interface:

import { OnDestroy } from '@angular/core';

Let's connect it to the class:

export class UserComponent implements OnDestroy { }

Now let's write our hook:

export class UserComponent implements OnDestroy { constructor() { console.log('constructor is started'); } ngOnDestroy() { console.log('onDestroy is applied'); } }

Make a reactive if with which the child component will be shown. Check the work of the studied hook.

The parent component has an array of user names. Make a child component with a user. Loop through the array and output components with users. Make a button that will delete elements from the array when clicked. Check that the deletion hook will be triggered in the child components.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline