Typescript 3 Angular 7 StopPropagation and PreventDefault not working

纵然是瞬间 提交于 2020-05-11 03:55:45

问题


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

回答1:


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




回答2:


You can only stop propagation for the same event.

Your fireEvent function stops propagation for your mousedown event, but not for your click event.

If you want to stop propagation to click, try to add another click event on the input and stop propagation from there

For instance

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

Your other function only needs to know what is required, that is, set focus

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

preventDefault() prevents the default behaviour, it is not related to bubbling or not the events, so you can safely ignore it



来源:https://stackoverflow.com/questions/55551821/typescript-3-angular-7-stoppropagation-and-preventdefault-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!