【问题标题】:Typescript 3 Angular 7 StopPropagation and PreventDefault not workingTypescript 3 Angular 7 StopPropagation 和 PreventDefault 不起作用
【发布时间】:2019-08-28 07:51:35
【问题描述】:

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

【问题讨论】:

    标签: javascript angular7 event-bubbling typescript3.0


    【解决方案1】:

    尝试使用 (click)="$event.stopPropagation()"。它可能会有所帮助,因为它在我的场景中对我有用。

    【讨论】:

      【解决方案2】:

      您只能停止同一事件的传播。

      您的 fireEvent 函数会停止传播您的 mousedown 事件,但不会停止传播您的 click 事件。

      如果您想停止传播点击,请尝试在输入上添加另一个点击事件并从那里停止传播

      例如

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

      你的其他功能只需要知道需要什么,即设置焦点

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

      preventDefault() 阻止默认行为,它与冒泡或事件无关,因此您可以放心地忽略它

      【讨论】:

        【解决方案3】:

        你有两个不同的事件,一个是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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-07
          • 1970-01-01
          • 2013-12-22
          • 2012-02-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多