Reputation:
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
Reputation: 39432
There are multiple ways you can do this:
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);
}
[(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
Reputation: 1863
Simply you can do like following,
<input type="text" (keyup.enter)="sendit($event.target.value)" />
sendit(data){
console.log("Value",data)
}
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
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