[英]Angular2 EventEmitter and preventDefault()
Angular2中有沒有辦法以某種方式阻止使用EventEmitter的事件的默認值?
我有以下場景:
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演示。 但是如果有人后來訂閱了這個陳詞濫調呢? 我的組件將再次在該觀察者之前調用,並且我的組件將不一致。
問題如何確保我的組件onClick()處理程序將在最后被調用,以保證其他觀察者之后不能阻止默認行為? 或者是否有完全不同的方式來實現我的目標?
要解決此問題,請在html模板中使用此方法
<button (click)="clickemitter(a,b,c); $event.stopPropagation();"
[style.color]="color" >
<ng-content></ng-content>
</button>
作為$event.stopPropagation();
用於停止默認點擊事件和你的按鈕只調用寫入(click)="...."
事件,這是clickemitter.emit(a,b,c)
也許這對你來說很有幫助。 謝謝。
只需使用return false;
這是我用來防止默認的代碼
@HostListener('click') open(){
this._isOpen = !this._isOpen;
return false;
}
並為stopPropagation
@HostListener('click', ['$event'])
onClick(e) {
alert("we have performed click");
e.stopPropagation();
}
我像這樣實現了event.preventDefault
export class ObserveComponent{
onSubmit(event:Event){
event.preventDefault();
}
}
每當我嘗試訪問對象中不存在的鍵的值時,停止頁面重新加載
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.