OnDestroy

export interface OnDestroy

exported from angular2/core defined in angular2/src/core/linker/interfaces.ts (line 189)

Implement this interface to get notified when your directive is destroyed.

ngOnDestroy callback is typically used for any custom cleanup that needs to occur when the instance is destroyed

Example (live example)

@Component({ selector: 'my-cmp', template: `<p>my-component</p>` }) class MyComponent implements OnInit, OnDestroy { ngOnInit() { console.log('ngOnInit'); } ngOnDestroy() { console.log('ngOnDestroy'); } } @Component({ selector: 'app', template: ` <button (click)="hasChild = !hasChild"> {{hasChild ? 'Destroy' : 'Create'}} MyComponent </button> <my-cmp *ngIf="hasChild"></my-cmp>`, directives: [MyComponent, NgIf] }) export class App { hasChild = true; } bootstrap(App).catch(err => console.error(err));

To create a stateful Pipe, you should implement this interface and set the pure parameter to false in the PipeMetadata.

A stateful pipe may produce different output, given the same input. It is likely that a stateful pipe may contain state that should be cleaned up when a binding is destroyed. For example, a subscription to a stream of data may need to be disposed, or an interval may need to be cleared.

Example (live demo)

In this example, a pipe is created to countdown its input value, updating it every 50ms. Because it maintains an internal interval, it automatically clears the interval when the binding is destroyed or the countdown completes.

import {OnDestroy, Pipe, PipeTransform} from 'angular2/core' @Pipe({name: 'countdown', pure: false}) class CountDown implements PipeTransform, OnDestroy { remainingTime:Number; interval:SetInterval; ngOnDestroy() { if (this.interval) { clearInterval(this.interval); } } transform(value: any, args: any[] = []) { if (!parseInt(value, 10)) return null; if (typeof this.remainingTime !== 'number') { this.remainingTime = parseInt(value, 10); } if (!this.interval) { this.interval = setInterval(() => { this.remainingTime-=50; if (this.remainingTime <= 0) { this.remainingTime = 0; clearInterval(this.interval); delete this.interval; } }, 50); } return this.remainingTime; } }

Invoking {{ 10000 | countdown }} would cause the value to be decremented by 50, every 50ms, until it reaches 0.

Members

ngOnDestroy()

Not Yet Documented