user10917344
user10917344

Reputation:

Angular on keyup.enter send the current text of an input to a method

I have an input which I want to get the text that it's currently got and send it to a method.

Here is the code:

app.component.html

<input type="text" (keyup.enter)="sendit()" />

app.component.ts

sendit() {
    console.log(The text in the input);
}

How do I do this?

Upvotes: 11

Views: 65636

Answers (3)

SiddAjmera
SiddAjmera

Reputation: 39432

There are multiple ways you can do this:

Use a template variable for the input. You'll get the value of it like this:

<input #yourInput type="text" (keyup.enter)="sendit(yourInput.value)" />

And in Component, get it like this:

sendit(inputValue) {
  console.log(inputValue);
}

Alternatively, you can also use [(ngModel)] to bind the text field two ways:

<input 
  type="text" 
  [(ngModel)]="bindedTwoWays"
  (keyup.enter)="sendit(bindedTwoWays)" >

And in Component:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  bindedTwoWays = 'Angular';

  sendit(inputValue) {
    console.log(inputValue);
  }
}

Here's a Working Sample StackBlitz with both the approaches for your ref.

Upvotes: 16

Karnan Muthukumar
Karnan Muthukumar

Reputation: 1863

Simply you can do like following,

<input type="text" (keyup.enter)="sendit($event.target.value)" />

 sendit(data){
    console.log("Value",data)
 }

enter image description here

Using Two way binding here is an solution,

how to get value from textbox using typescript in angular 2

I hope it's helps to you.

Thanks,

Muthu

Upvotes: 19

Suren Srapyan
Suren Srapyan

Reputation: 68635

Create a template variable for the input element and pass your input value like this

<input #inp type="text" (keyup.enter)="sendit(inp.value)" />
       ^^^^                                   ^^^^^^^^^

Accept via

sendit(inputValue) {
    console.log(inputValue);
}

Upvotes: 2

Related Questions