Typescript 3 Angular 7 StopPropagation和PreventDefault不起作用 [英] Typescript 3 Angular 7 StopPropagation and PreventDefault not working

查看:358
本文介绍了Typescript 3 Angular 7 StopPropagation和PreventDefault不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在div内输入了文本.单击输入应将其设置为焦点并停止div click事件的冒泡.我已经在文本输入事件上尝试了stopPropagationpreventDefault,但无济于事.控制台日志显示div单击仍然执行.如何停止div点击事件的执行?

I have a text input inside a div. Clicking on the input should set it to focus and stop the bubbling of the div click event. I've tried the stopPropagation and preventDefault on the text input event but to no avail. The console logs shows that the div click still executes regardless. How to stop the div click event from executing?

// html
<div (click)="divClick()" >
  <mat-card mat-ripple>
    <mat-card-header>
      <mat-card-title>
        <div style="width: 100px">
          <input #inputBox matInput (mousedown)="fireEvent($event)" max-width="12" />
        </div>
      </mat-card-title>
    </mat-card-header>
  </mat-card>
</div>


// component
@ViewChild('inputBox') inputBox: ElementRef;
divClick() {
    console.log('click inside div');
}

fireEvent(e) {
    this.inputBox.nativeElement.focus();
    e.stopPropagation();
    e.preventDefault();
    console.log('click inside input');
    return false;
}

推荐答案

您有两个不同的事件,一个是mousedown,另一个是click.

You have two different events, one is mousedown and another is click.

仅当两个事件属于同一类时,e.stopPropagation()才起作用.

The e.stopPropagation() only works if both of the events are of the same kind.

您可以像这样更改输入以使其按预期工作:

You can change the input like this to work as expected:

<input #inputBox matInput (click)="fireEvent($event)" max-width="12" />

实时示例: https://stackblitz.com/edit/angular-material-basic-stack-55598740?file=app/input-overview-example.ts

这篇关于Typescript 3 Angular 7 StopPropagation和PreventDefault不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆