0

My template is:

<form class="navbar-form"> <div class="input-group no-border"> <input type="text" #term class="form-control" (keyup.enter)="search($event)" placeholder="поиск..." /> <button type="button" class="btn btn-white btn-round btn-just-icon" (click)="search($event)"> <i class="material-icons">search</i> <div class="ripple-container"></div> </button> </div> </form> 

Method search() is:

 search(e): boolean { e.preventDefault(); this.router.navigate(['users']); } 

Why despite e.preventDefault(); page is reloaded after enter key pressed?

I have removed (keyup.enter)="search($event)" it still reload page. It means somewhere else events called

5
  • 1
    Because preventDefault() affects only the event, but not the code after. Commented Jul 28, 2020 at 15:44
  • I know, but instead moving to route page I get reload page. Commented Jul 28, 2020 at 15:49
  • Then, I would assume, that issue connected to your routing setup. Could you post it here? Commented Jul 28, 2020 at 15:51
  • I commented this.router.navigate(['users']); the same problem Commented Jul 28, 2020 at 15:54
  • Probably, you should remove the return type as long as the function returns nothing. I just tested your code (without the router) does reload. I suspect you have a routing problem, can you post your routing config please? Commented Jul 28, 2020 at 16:09

2 Answers 2

2

The problem is the <form> is handling the keydown event before the <input> does, so you can use keydown.enter on your <input> instead.

Also, your function does not quite return boolean, you can use void there (this doesn't apply to your question, just advice).

component.html

<form class="navbar-form" > <div class="input-group no-border"> <input type="text" #term class="form-control" (keydown.enter)="search($event)" placeholder="поиск..." /> <button type="button" class="btn btn-white btn-round btn-just-icon" (click)="search($event)"> <i class="material-icons">search</i> <div class="ripple-container"></div> </button> </div> </form> 

component.ts

 search(e): void { e.preventDefault(); this.router.navigate(['users']); } 
Sign up to request clarification or add additional context in comments.

1 Comment

If you still need to use keyup and not keydown you can add to the form something like this <form (submit)="$event.preventDefault()"> .
1

Use "double elimination" strategy to completly stop the event:

e.preventDefault(); e.stopPropagation(); 

8 Comments

When I do click it work fine, when key.enter it reloads
Is it all code? Remove search from the input and check once more
I have removed, it still reloaded, how to find where is catcher?
One more try please, change <form> tag to <div> and do one more test
May be it is better to open another question? Btw, @Suren answer is way better than my :)
|