Chrillewoodz Chrillewoodz - 1 month ago 19
TypeScript Question

Input and outputs, how to work with them to follow the naming convention of the Angular 2's styleguide?

Before I knew any better I used to have my directive defined like this:

...
inputs: [
'onOutside'
]
...

export class ClickOutsideDirective {
@Output() onOutside: EventEmitter<any> = new EventEmitter();
}


But then I read the styleguide and it said that you should not prefix your outputs with
on
since Angular 2 supports the
on-
syntax in the templates.

So I'm trying to change it to something like:

@Input() outsideClick: any;
@Output() outsideClick: EventEmitter<any> = new EventEmitter();


However, I'm finding it difficult to separate the
@Input
name from the
Output
name if you aren't allowed to use the
on
prefix.

Before you could name both the
@Input
and
@Output
the same thing but if declaring both within the exported class then this no longer works since an error will be thrown.

If I name the
@Input
to
outside
and the
@Output
to
outsideClick
, it doesn't really make sense since both of them are the same thing.
outside
is the function I want to execute when calling
outsideClick
.

Also,
outsideClick
won't know what to execute if
outside
isn't name the same thing anymore, or am I missing something?

How should I approach naming the
@Input
and
@Output
variables here so that it still works and makes as much sense as it did in the first example?

EDIT:

Usage example:

<div clickOutside [exceptions]="['.toggler']" (outside)="doSomethingOnOutsideClick()"></div>

Answer

Definitely don't use on. In JavaScript events also don't start with on. Only the event handlers do. There is no onClick event in JS. The event name is click and if you assign a function to onClick this function will be called when the click event was received.

If you have inputs and outputs that belong together name them

@Input() name:any; 
@Output() nameChange: EventEmitter<any> = new EventEmitter();;

This allows the short hand for Angular2 "two-way binding"

[(name)]="someProp"

If you use @Input() and @Output() (preferred way) then you don't need inputs: [] and outputs: []. These are two ways to do the same thing and if you use both one is redundant.

To match the browser naming scheme what you could do is

(nameChange)="onNameChange($event)"

to have an event handler onNameChange to be called when the nameChange event is received.

When the event is not part of an input/output pair you can or should omit the Change

(loggedIn)="onLoggedIn($event)
Comments