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

折月煮酒 提交于 2020-07-20 07:28:08

问题


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> 

回答1:


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)


来源:https://stackoverflow.com/questions/39930326/input-and-outputs-how-to-work-with-them-to-follow-the-naming-convention-of-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!