Get value from Input text field in angular 5

56,395

Solution 1

You have wrong bound. You need banana-in-box binding [(ngModel)]="serial" instead of [ngModel]="serial"

() in the binding will update serial model everytime when the input will be changes. From input into model

Single [] will just bind the data of serial if it will be changed by code manually. This will cause to one-way binding - from model into input.

As you guess - together [()] they will make two-way binding.

Solution 2

this is one way binding. from view to controller.

file code.component.html

<label >Code</label>
<input (input)="tcode=$event.target.value" type="text" class="form-control">
<button class="btn btn-success" (click)="submit()">Submit</button>

file code.component.ts

tcode : string;
submit() {
    console.log("the code :" + this.tcode);
}
Share:
56,395
Sithys
Author by

Sithys

https://www.poolarino.de

Updated on July 25, 2022

Comments

  • Sithys
    Sithys almost 2 years

    it seems to be an easy question, but nothing what i found worked for me. I have a standard input field in my component.html:

    <div class="form-group">
        <label>Serial</label>
        <input type="text" name="serial" id="serial" [ngModel]="serial" [value]="serial" class="form-control">
    </div>
    

    So when the user now submitts the form, how do i get the value he typed into the field? If i do a simple console.log(this.serial) in my onSubmit() function, i get nothing. I declared serial: String; in my component.ts

  • Suren Srapyan
    Suren Srapyan about 6 years
    You are welcome. But try to understand what is going. This is one of the core concepts in Angular
  • Illep
    Illep almost 6 years
    How did you retrieve the value from type script ?
  • Suren Srapyan
    Suren Srapyan almost 6 years
    @Illep In typescript class you already have a property with name serial which is the bound one. So you need just to access this property and get the latest value
  • specialk1st
    specialk1st about 5 years
    Thank you for this simple example. Much appreciated.