Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
54
rated 0 times [  59] [ 5]  / answers: 1 / hits: 91414  / 5 Years ago, sat, april 6, 2019, 12:00:00

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

More From » angular7

 Answers
73

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


[#52293] Monday, April 1, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nestorjarettg

Total Points: 451
Total Questions: 108
Total Answers: 108

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
;