使用鼠标事件防止单击角度2

时间:2016-02-29 22:29:10

标签: angular

如何阻止click事件从同一元素中的mousedown / mouseup事件调度?

我已经尝试过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;
}

2 个答案:

答案 0 :(得分:0)

你想做什么? 如果您想显示一个消息框以确认您的解决方案是有效的,请在显示消息框之后显示cos,未触发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();
    }
  }
}

答案 1 :(得分:0)

您的指令有效地阻止了单击冒泡到父元素,但不防止单击冒泡到SAME元素。因此,您可以在要阻止单击的元素的子组件上使用相同的指令 - 或者它的修剪版本。

指令:

@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