how to prevent a page from cooling when I enter an input (form) in angle 4?

0

I'm trying to make a search engine, which basically is a form with an input and a button. I want that when writing in the input and when giving enter, I send the parameter my typescript module. without it recharging. I am a beginner in angular 4.

This is the form of my view ..

  <form class="form-inline my-2 my-lg-0" >
      <input class="form-control mr-sm-2" type="search" placeholder="Buscar Héroe" aria-label="Search" (keyup.enter)="buscarHeroe(buscarTexto.value)" #buscarTexto>
      <button (click)="buscarHeroe(buscarTexto.value)" class="btn btn-outline-success my-2 my-sm-0" type="button">Buscar</button>
    </form>

I'm trying to get the value to be received nothing more, just to test.

this is the function of my typescript component

  buscarHeroe(termino:string){
    console.log(termino);
  }

Yes, I do not know if it's the right way, I'm missing something? by pressing the button, if it works. but when writing in the input and give enter. this refreshes the page. I await your response!

    
asked by JuanL 30.04.2018 в 02:31
source

2 answers

0

I've been in angular for a short time (about two months) but I can still give you a cable. When working in angular (both angular 5 and angularjs) and you want the data of a text box (or any other input) to be received in the code, you must use a binding.

What is a binding ?: A binding is a way to "link" the data of an input field, with a variable of your controller.

Example:

control.ts

...
textoInput: string; //Indicas que creas una variable tipo string
...
imprimirString() {
    console.log(textoImput);
}

vista.html

...
<input id="inputText" [(ngModel)]=textoInput (ngModelChange)="imprimirString()">
...

With [(ngModel)] = textImput what you are doing is to link the value that the user enters in the input to the variable textImput.

With (ngModelChange) what you do is control which method is executed when the input content changes.

With this, every time you change the text, the printString () method will be launched, which takes the content of the input as a console.

    
answered by 08.05.2018 в 13:23
0

I hope not to arrive too late, I think that if you are not going to use the form, because you do not need the refresh, what you should do is change the form tags by div, so that you do not do that submit involuntarily.

<div class="form-inline my-2 my-lg-0" >
  <input class="form-control mr-sm-2" type="search" placeholder="Buscar Héroe" aria-label="Search" (keyup.enter)="buscarHeroe(buscarTexto.value)" #buscarTexto>
  <button (click)="buscarHeroe(buscarTexto.value)" class="btn btn-outline-success my-2 my-sm-0" type="button">Buscar</button>
</div>

That way even if your button was of the submit type, it would not be sent anywhere.

Greetings.

    
answered by 13.07.2018 в 09:15