Angular2 EventEmitter and preventDefault ()

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) //gets called before the observers of clickemitter this.color = "red"; else this.color = "blue"; } } @Component({ selector: 'my-app', providers: [], template: ` <my-component (clickemitter)="$event.preventDefault()">Hello Angular</my-component> `, directives: [MyComponent] }) export class App { constructor() { } } 

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?

+5
source share
3 answers

Just use return false;
here is the code i used to prevent by default

  @HostListener('click') open(){ this._isOpen = !this._isOpen; return false; } 

And for stopPropagation

  @HostListener('click', ['$event']) onClick(e) { alert("we have performed click"); e.stopPropagation(); } 
+5
source

To solve this problem, use this in your html template

 <button (click)="clickemitter(a,b,c); $event.stopPropagation(); [style.color]="color"><ng-content></ng-content></button> 

Like $ event.stopPropagation (); works to stop the default click event, and your button triggers a call event that is written (click) = "...." which is clickemitter.emit (a, b, c)

May this help you. Thanks.

+4
source

I implemented event.preventDefault, like this

 export class ObserveComponent{ onSubmit(event:Event){ event.preventDefault(); } } 

stop reloading the page every time I tried to access the value of a key that is not in the object

0
source

Source: https://habr.com/ru/post/1244217/


All Articles