Skip to content

Instantly share code, notes, and snippets.

@davidhenley
Last active September 10, 2019 21:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidhenley/8bdc4fb16c5db7e4adfc87407f9d4d1d to your computer and use it in GitHub Desktop.
Save davidhenley/8bdc4fb16c5db7e4adfc87407f9d4d1d to your computer and use it in GitHub Desktop.
Angular Hooks
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