Angular 2 - What are recomanditions for @Output event names (to prevent native event name collision)

135 views
Skip to first unread message

Milan Lempera

unread,
Oct 26, 2016, 8:03:31 AM10/26/16
to Angular
Hello, 

I have played with Angular 2 components and their compositions and I have run into ugly behavior, which is caused by native event bubbling and @Output name collision.

I have component app-form with form in template

<form (ngSubmit)="submitButtonClicked($event)">
<input type="text"/>
<button type="submit">Send</button>
</form>

I use this form component in app-middle component, which has own event emiter with name submit.

@Component({
selector: 'app-middle',
templateUrl: './middle.component.html',
styleUrls: ['./middle.component.css']
})
export class MiddleComponent implements OnInit {

@Output() submit = new EventEmitter<string>();

constructor() { }

emitSubmitEvent() {
this.submit.emit("some data");
}

}

template:

<div>

<app-form></app-form>

</div>

And app component with template:

<app-middle (submit)="submitListener($event)"></app-middle>

Now, submitListener will be called
  - when submit on app-middle is called (wanted behavior)
 - when form is submitted, because native event buble to the top ("parasitic" behavior)

I supose, "parasitic" behavior is based on DOM event bubling. 
I can stop it by event.stopPropagation() in submitButtonClicked handler, but if i forgot stop it, i get pretty ugly errors.

Generally I consider this behavior quite dangerous. If I am not wrong, every event binding expression hander can be potentialy called "parasiticly" by native event from inner components.
 if has same name as any of DOM events (https://developer.mozilla.org/en-US/docs/Web/Events) And I don't talk about forward compatibility....

Same problem you can see here: https://bitbucket.org/winsik/submit-event-issue/src

Did you run into this problem? How do you name your @Outputs?

Milan Lempera

unread,
Oct 27, 2016, 12:57:26 AM10/27/16
to Angular

Sander Elias

unread,
Oct 31, 2016, 12:15:54 AM10/31/16
to Angular
Hi Milan,

To start off, this behaviour is not specific to Angular. It happens in all systems that have events that bubble up, wich turns out to be almost all systems that use a DOM-like structure.
It is something that you need to be aware off, and, is a danger in most systems that are using event's to communicate. 

What you can do is don't give your app-specific events generic/common names. Also using a pre/suffix in your event names help. If needed, you can even give specific parts of your app their own pre/suffix.

Hope that helps you a bit,
Regards
Sander


Reply all
Reply to author
Forward
0 new messages