TransWikia.com

How to prevent button form Angular?

Stack Overflow Asked by user13976004 on November 20, 2020

I have a search form:

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

It should search by click and key.enter:

search(): void {
   const value = this.term.nativeElement.value ? this.term.nativeElement.value.toString().trim() : null;
   this.router.navigate(['search?=' + value]);

Problem is when I click over button it reloads page. Also I don’t like condition const value = this.term.nativeElement.value ? this.term.nativeElement.value.toString().trim() : null;

How can I improve it?

I have tried to pass $event: search($event).

search(e) {
   e.eventPrevent();
}

It does not work for me.

5 Answers

Please use preventDefault()

private search(event){
  event.preventDefault()
}

and this to prevent default submit behavior (reload)

<form (submit)="$event.preventDefault()"> 

Correct answer by Thái Bùi Minh on November 20, 2020

Add type="button"

<button class="btn btn-white btn-round btn-just-icon" type="button (click)="search()">

and make search function return false

Answered by thepowerlies on November 20, 2020

Just use type="button". For explanation see https://www.w3schools.com/jsref/prop_pushbutton_type.asp

Answered by Pavel Gatnar on November 20, 2020

in your particular example I would replace the wrapping <form> tag with just <div>. that will do the trick and everything should work

Answered by Andrei on November 20, 2020

It should be:

e.preventDefault();

Answered by msmolcic on November 20, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP