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()處理程序將在最後被調用,以保證沒有其他觀察者可以阻止默認行爲,後來呢?還是有完全不同的方式來實現我的目標?
謝謝,這有助於一個虛擬組件中的表單觸發父組件中提交事件「提交」的提交。 – daddywoodland