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