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

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

问题描述

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

//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"/>

</mat-card-title></mat-card-header></mat-card>

//成分@ViewChild('inputBox') inputBox: ElementRef;divClick() {console.log('点击里面的div');}火事件(e){this.inputBox.nativeElement.focus();e.stopPropagation();e.preventDefault();console.log('点击内部输入');返回假;}

解决方案

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

e.stopPropagation() 仅在两个事件类型相同时才有效.

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

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

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;
}

解决方案

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

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" />

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

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

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆