Angular 4 - get input value

后端 未结 9 1555
抹茶落季
抹茶落季 2021-02-01 00:41

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 m

相关标签:
9条回答
  • 2021-02-01 01:18

    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.

    0 讨论(0)
  • 2021-02-01 01:19

    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);}
    
    0 讨论(0)
  • 2021-02-01 01:21

    In HTML add

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

    And in component Add

    onKey(event) {const inputValue = event.target.value;}
    
    0 讨论(0)
  • 2021-02-01 01:21

    You can also use template reference variables

    <form (submit)="onSubmit(player.value)">
       <input #player placeholder="player name">
    </form>
    
    onSubmit(playerName: string) {
      console.log(playerName)
    }
    
    0 讨论(0)
  • 2021-02-01 01:33

    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. LearnersModules is the module file on our Angular files SaveSampleExams is the service file is one function method.

    >  this.service.SaveSampleExams(LearnersModules).subscribe(
    >             (data) => {
    >               this.dataSaved = true;
    >               LearnersModules.txtValue = this.txtValue.value; 
    >              });
    
    0 讨论(0)
  • 2021-02-01 01:36
    <form (submit)="onSubmit()">
       <input [(ngModel)]="playerName">
    </form>
    
    let playerName: string;
    onSubmit() {
      return this.playerName;
    }
    
    0 讨论(0)
提交回复
热议问题