Is there any way in Angular2 to somehow prevent the default for events using EventEmitter?
I have the following script:
import {Component, Output, EventEmitter} from 'angular2/core' @Component({ selector: 'my-component', template: `<button (click)="clickemitter.emit($event); onClick($event)" [style.color]="color"><ng-content></ng-content></button>` }) export class MyComponent { @Output clickemitter: EventEmitter<MouseEvent> = new EventEmitter(); private color: string = "black"; constructor() { } private onClick(event: MouseEvent): void { if(!event.defaultPrevented)
I also made Plunker for this: https://plnkr.co/edit/yIoF1YgvkiZLBPZ6VHTs?p=preview
Problem If I click on a button, the color of the button will not turn blue as it should, but instead it will turn red. Perhaps this is due to the fact that EventEmitter.emit () / next () seems to work asynchronously. I tried to solve this problem by also signing my onClick () method on the emitter and just calling clickemitter.emit ($ event) in the button's event handler (click). This will work to demonstrate Plunker when I did this in ngAfterInit (). But what if someone later joins the clicker? My component will be called before this observer, and my component will be inconsistent.
Question How can I make sure that my onClick () component handler is called for the last time to ensure that no other observer can prevent the default behavior after that? Or is there a completely different way to achieve my goal?
source share