95

I would like to know how to get the value from an input on angular 4. I looked over the documentation on angular and the example with the key event doesn't work very well for me and I can't find a proper example how to do this so please help me out

The problem: I try to read the input's value and after submiting the value to another component that will add the value to a select tag(e.g. send the name of the person to a list for a select tag)

My code

lenilsondc
  • 9,590
  • 2
  • 25
  • 40
Daniel Bisceanu
  • 1,117
  • 1
  • 9
  • 15

11 Answers11

91
<form (submit)="onSubmit()">
   <input [(ngModel)]="playerName">
</form>

let playerName: string;
onSubmit() {
  return this.playerName;
}
yala ramesh
  • 3,362
  • 1
  • 22
  • 35
  • 4
    This works, but using ngModel is deprecated in Angular 6 and will be removed in Angular 7. https://angular.io/api/forms/FormControlName#use-with-ngmodel – Daniel Dec 06 '18 at 20:30
  • 19
    The referenced Angular documentation does not announce the deprecation of ngModel, but the deprecation of ngModel for *reactive Forms*. It's still valid for all other use cases. – Jens Habegger Mar 05 '19 at 11:53
  • 2
    Make sure you import the FormsModule in your app Module so you can use ngModel! https://angular.io/guide/built-in-directives#displaying-and-updating-properties-with-ngmodel – AlyssaNicoll Jul 20 '21 at 17:35
64

In HTML add

<input (keyup)="onKey($event)">

And in component Add

onKey(event) {const inputValue = event.target.value;}
laiju
  • 1,353
  • 10
  • 17
23

If you dont want to use two way data binding. You can do this.

In HTML

<form (ngSubmit)="onSubmit($event)">
   <input name="player" value="Name">
</form>

In component

onSubmit(event: any) {
   return event.target.player.value;
}
Martin M.
  • 503
  • 5
  • 10
22

html

<input type="hidden" #fondovalor value="valores">
     <button (click)="getFotoFondo()">Obtener</button>

ts

@ViewChild('fondovalor') fondovalor:ElementRef;

getFotoFondo(){ 
        const valueInput = this.fondovalor.nativeElement.value
}
Web Nexus
  • 1,150
  • 9
  • 28
9

You can also use template reference variables

<form (submit)="onSubmit(player.value)">
   <input #player placeholder="player name">
</form>
onSubmit(playerName: string) {
  console.log(playerName)
}
Cichy
  • 4,602
  • 3
  • 23
  • 28
8

I think you were planning to use Angular template reference variable based on your html template.

 // in html
 <input #nameInput type="text" class="form-control" placeholder=''/>

 // in add-player.ts file
 import { OnInit, ViewChild, ElementRef } from '@angular/core';

 export class AddPlayerComponent implements OnInit {
   @ViewChild('nameInput') nameInput: ElementRef;

   constructor() { }

   ngOnInit() { }

   addPlayer() {
     // you can access the input value via the following syntax.
     console.log('player name: ', this.nameInput.nativeElement.value);
   }
 }
Jun
  • 2,942
  • 5
  • 28
  • 50
  • please answer to this : https://stackoverflow.com/questions/67103410/how-to-get-input-type-numbers-value-before-submitting – raghu raman Apr 15 '21 at 07:00
7

You can use (keyup) or (change) events, see example below:

in HTML:

<input (keyup)="change($event)">

Or

<input (change)="change($event)">

in Component:

change(event) {console.log(event.target.value);}
Harrison O
  • 1,119
  • 15
  • 20
  • please answer to this : https://stackoverflow.com/questions/67103410/how-to-get-input-type-numbers-value-before-submitting – raghu raman Apr 15 '21 at 07:00
6

If you want to read only one field value, I think, using the template reference variables is the easiest way

Template

<input #phone placeholder="phone number" />

<input type="button" value="Call" (click)="callPhone(phone.value)" />

**Component** 
 
callPhone(phone): void 
{
  
console.log(phone);

}

If you have a number of fields, using the reactive form one of the best ways.

Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46
sourcecode
  • 4,116
  • 1
  • 20
  • 14
  • please answer to this: https://stackoverflow.com/questions/67103410/how-to-get-input-type-numbers-value-before-submitting – raghu raman Apr 15 '21 at 07:01
2

In Angular 11, if you have your template set up so that you have a form tag which contains the input tag and there also exists a button that you can click, the following code shows how to alert the input tag's value via two-way data binding:

app.component.html:

<form>
  <input [(ngModel)]="example" name="example">
  <button (click)="alert()">Alert</button>
</form>

app.component.ts:

example: string;

alert() {
  alert(this.example);
}

Note that the name attribute in the template is required here, otherwise you'll get an error message in the developer console saying the following:

Error: If ngModel is used within a form tag, either the name attribute must be set or the form
  control must be defined as 'standalone' in ngModelOptions.

  Example 1: <input [(ngModel)]="person.firstName" name="first">
  Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">
aleksejjj
  • 1,405
  • 2
  • 18
  • 28
0

HTML Component

<input type="text" [formControl]="txtValue">

TS Component

public txtValue = new FormControl('', { validators:[Validators.required] });

We can use this method to save using API. LModules is the module file on our Angular files SaveSampleExams is the service file is one function method.

>  this.service.SaveSampleExams(LModules).subscribe(
>             (data) => {
>               this.dataSaved = true;
>               LearnersModules.txtValue = this.txtValue.value; 
>              });
0

This is the method I like to use. The reason I prefer this method is that you can reference the input value in functions other than the one you've directly attached to the form, and you can also add validators and pre-set values if you wish:

import {
  FormBuilder,
  FormGroup,
  Validators, FormsModule, ReactiveFormsModule
} from '@angular/forms';

@Component({
  selector: 'test-app',
  templateUrl: './test-app.component.html',
  styleUrls: ['./test-app.component.scss']
})
export class SearchUsersComponent implements OnInit {

  testForm!: FormGroup;

  constructor(
    private formBuilder: FormBuilder,
  ) {}

  async ngOnInit(): Promise < void > {

    this.testForm = this.formBuilder.group({
      input1: "",
      input2: "",
    });

    this.testForm.controls['input1'].setValue("test1"); //here you can preset values if you wish.

  }

  submitForm() {
    console.log(this.testForm.get('input1')?.value)
    console.log(this.testForm.get('input2')?.value)
  }
}
<div [formGroup]="testForm">
  <mat-form-field appearance="fill" floatLabel="never">
    <input matInput placeholder="First Input" formControlName="input1" />
  </mat-form-field>
  <mat-form-field appearance="fill" floatLabel="never">
    <input matInput placeholder="First Input" formControlName="input2" />
  </mat-form-field>
  <div>
    <button mat-flat-button class="btn-small" (click)="submitForm()"> </button>
  </div>
</div>