Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript 3 Angular 7 StopPropagation and PreventDefault not working

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; } 
like image 254
user1019042 Avatar asked Apr 06 '19 17:04

user1019042


People also ask

How do you stop events bubbling in typescript?

Try with (click)="$event. stopPropagation()" .

What is the difference between event stopPropagation () and event preventDefault ()?

The event. preventDefault() will not allow the user to leave the page and open the URL. The event. stopPropagation() method stops the propagation of an event from occurring in the bubbling or capturing phase.

Does preventDefault stop propagation?

preventDefault() prevents the default browser behavior for a given element. stopPropagation() stops an event from bubbling or propagating up the DOM tree. Whereas, return false is a combination of both preventDefault() and stopPropagation() .

What is event stopPropagation () in angular?

The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.


1 Answers

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

like image 98
Daniel Piñeiro Avatar answered Sep 21 '22 08:09

Daniel Piñeiro