-
Notifications
You must be signed in to change notification settings - Fork 27.1k
Description
According to the docs, making a directive that listens for events on the host element is like so:
@Directive({
selector: 'input',
hostListeners: {
'change': 'onChange($event)',
'window:resize': 'onResize($event)'
}
})
class InputDirective {
onChange(event:Event) {}
onResize(event:Event) {}
}This seems like it could be streamlined:
- The listeners are registered far away from where the handlers are defined
- The registration duplicates a) the method names and b) arguments.
- The registration uses strings which makes obfuscation and refactoring more difficult.
- You can listen for global events, too (seems odd that the hostListener object lets you do this)
- Listening for global events depends on a magic string prefix of "window:" (or "document:" or "body:", implied by the docs)
Here's a possible alternative:
@Directive({
selector: 'input'
})
class InputDirective {
@HostListener('change')
onChange(event: Event) {}
@WindowListener('resize')
onResize(event: Event) {}
}This doesn't suffer from any of the problems listed above.
You can imagine a similar streamlining for properties. Currently you write:
@Directive({
selector: '[dependency]',
properties: {
'id':'dependency'
}
})
class Dependency {
id:string;
}But using decorators you could write:
@Directive({
selector: '[dependency]',
})
class Dependency {
@Property('dependency')
id:string;
}I find it a whole lot easier to understand this, not needing to remember constantly what the left and right hand side of the configuration means. E.g. for { 'id': 'dependency' } I cannot tell easily which one of 'id' or 'dependency' is the JS class property and which is the DOM element property. I constantly get this confused in Angular 1, too, with the scope config. Hopefully we can eliminate this rough edge in Angular 2...