One of the nice underused features of Angular is the support for decorators (through Typescript).
From the Typescript documentation:
A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators use the form
@expression
, whereexpression
must evaluate to a function that will be called at runtime with information about the decorated declaration.
A nice example of the usage of decorators is the ngx-auto-unsubscribe library. This Class decorator that will automatically unsubscribe from observable subscriptions when the component is destroyed.
An example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { AutoUnsubscribe } from "ngx-auto-unsubscribe"; | |
@AutoUnsubscribe() | |
@Component({ | |
selector: 'inbox' | |
}) | |
export class InboxComponent { | |
one: Subscription; | |
two: Subscription; | |
constructor( private store: Store<any>, private element : ElementRef ) {} | |
ngOnInit() { | |
this.one = store.select("data").subscribe(data => // do something); | |
this.two = Observable.interval.subscribe(data => // do something); | |
} | |
// This method must be present, even if empty. | |
ngOnDestroy() { | |
// We'll throw an error if it doesn't | |
} | |
} |