2016-03-01 132 views
4

Angular2有沒有辦法阻止使用EventEmitter的事件的默認值?Angular2 EventEmitter and preventDefault()

我有以下情形:

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() { 

    } 
} 

我做了一個Plunker這一點,太:https://plnkr.co/edit/yIoF1YgvkiZLBPZ6VHTs?p=preview

的問題 如果我在按鈕上單擊該按鈕的顏色不會變成藍色,但它變成了紅色。 這可能是因爲EventEmitter.emit()/ next()似乎是異步的。 我試圖通過在發射器上訂閱我的onClick()方法來解決此問題,並在我的按鈕(單擊)事件處理函數中調用clickemitter.emit($ event)。當我在ngAfterInit()中完成時,這將對Plunker Demo有效。但是如果某人稍後訂閱了clickemitter呢?我的組件會再次在該觀察者之前被調用,並且我的組件會不一致。

問題 我怎麼能保證我的組件的onClick()處理程序將在最後被調用,以保證沒有其他觀察者可以阻止默認行爲,後來呢?還是有完全不同的方式來實現我的目標?

回答

0

我實現event.preventDefault這樣

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

停止重新加載頁面每次我試圖訪問一個關鍵的值未在對象

4

存在只要使用return false;
這裏是代碼我已經使用了防止默認

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

而對於stopPropagation

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

爲了解決這個問題,在您的HTML模板使用

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

至於$ event.stopPropagation(); (點擊)=「....」,這是clickemitter.emit(a,b,c)

可以幫助您完成這些幫助。謝謝。

+0

謝謝,這有助於一個虛擬組件中的表單觸發父組件中提交事件「提交」的提交。 – daddywoodland