2016-02-29 110 views
3

如何防止從同一元素中的mousedown/mouseup事件派發點擊事件?防止用鼠標事件點擊角度2

我已經嘗試過evt.preventDefault和evt.stopPropagation,但它似乎沒有工作。見例如plunker here

<div> 
    <h2 (click)="onClickToBePrevented()" mouseEvents> 
    Click Here 
    </h2> 
</div> 

指令mouseevents:

@(host: { 
    '(mousedown)': "preventClick($event)", 
    '(mouseup)': "preventClick($event)" 
}) 
preventClick(evt){ 
    evt.preventDefault(); 
    evt.stopPropagation(); 

    return false; 
} 
+0

這裏http://stackoverflow.com/questions/8643739/cancel-click-閱讀答案鼠標事件處理程序,它會給你一個發生了什麼的想法。 –

回答

0

那你想幹什麼? 如果您想顯示一個消息框以確認您的解決方案是否正常工作,請在通過mousedown顯示消息框之後點擊,Click事件未被觸發,並且您可以手動觸發它。 你不需要調用任何方法來阻止它。 實施例plunker here

@Component({ 
    selector: 'app', 
    template: ` 
<div (click)="onClick()" [confirm]="onClick" 
    confirmMessage="Are you ready!">click me!</div> 
    ` 
}) 
export class AppComponent { 
    onClick() { 
    console.log('Everything you can do'); 
    } 
} 

///

@Directive({ 
selector: `[confirm]` 
    host:{ 
    "(mousedown)":"confirmFirst()", 
    } 
}) 
export class ConfirmDirective { 
    @Input('confirm') onConfirmed: Function =() => {}; 
    @Input() confirmMessage: string = 'Are you sure you want to do this?'; 

    confirmFirst() { 
    const confirmed = window.confirm(this.confirmMessage); 

    if(confirmed) { 
     this.onConfirmed(); 
    } 
    } 
} 
+0

但這並不回答原來的問題,這在某些情況下是有效的。 – FrontierPsycho

0

你的指令有效地防止點擊鼓泡向父元素,但不是相同的元件。因此,您可以在要防止點擊的元素的子組件上使用相同的指令 - 或其修剪版本。

指令:

@Directive({ 
    selector: '[preventClick]', 
    host: { 
    '(click)': "preventClick($event)" 
    } 
}) 
class PreventClick { 
    preventClick(evt){ 
    evt.stopPropagation(); 
    console.log('Click prevented!'); 
    } 
} 

組件:

@Component({ 
    selector: 'my-app', 
    providers: [], 
    template: ` 
    <div> 
     <h2 (click)="onClick()"> 
     <span preventClick>Hello {{name}}</span> 
     </h2> 
     <div>{{clickResult}}</div> 
    </div> 
    `, 
    directives: [PreventClick] 
}) 
export class App { 
    private preventResult:string; 
    private clickResult:string; 

    constructor() { 
    this.name = 'Angular2' 
    this.clickResult = "Try clicking the header" 
    } 

    onClick(){ 
    this.clickResult = "No, it doesn't work :("; 
    } 
} 

見plunker: http://plnkr.co/edit/9Cpt6N?p=preview

+0

順便說一句我刪除(mouseup)和(mousedown)主機事件綁定,因爲他們沒有觸發點擊,但他們可以使用,唯一的影響是該指令將被稱爲不止一次。 –