Last active
September 10, 2019 21:37
-
-
Save davidhenley/8bdc4fb16c5db7e4adfc87407f9d4d1d to your computer and use it in GitHub Desktop.
Angular Hooks
This file contains hidden or 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 { Component } from '@angular/core'; | |
@Component({ | |
selector: 'hooks-example', | |
template: ` | |
<p>You clicked {{count}} times</p> | |
<button (click)="setCount(count + 1)">Click Me</button> | |
` | |
}) | |
export class HooksComponent { | |
@UseState(0) count; setCount; | |
@UseEffect() onEffect() { | |
document.title = `You clicked ${this.count} times`; | |
} | |
} | |
function UseState(seed: any) { | |
return function(target: Object, key: string) { | |
target[key] = seed; | |
target[`set${key.replace(/^\w/, c => c.toUpperCase())}`] = val => target[key] = val; | |
} | |
} | |
function UseEffect() { | |
return function(target: Object, key: string, descriptor: PropertyDescriptor) { | |
target.ngOnInit = descriptor.value; | |
target.ngAfterViewChecked = descriptor.value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment