首页 > 解决方案 > Typescript 3 Angular 7 StopPropagation 和 PreventDefault 不起作用

问题描述

我在 div 中有一个文本输入。单击输入应将其设置为焦点并停止 div 单击事件的冒泡。我已经在文本输入事件上尝试了stopPropagationand preventDefault,但无济于事。控制台日志显示 div click 仍然执行。如何停止执行 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" />
        </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;
}

标签: javascriptangular7event-bubblingtypescript3.0

解决方案


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

e.stopPropagation() 仅在两个事件属于同一类型时才有效。

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

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

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


推荐阅读