Angular 4 - get input value

2020-05-25 04:49发布

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

7条回答
家丑人穷心不美
2楼-- · 2020-05-25 04:56

You can also use template reference variables

<form (submit)="onSubmit(player.value)">
   <input #player placeholder="player name">
</form>
onSubmit(playerName: string) {
  console.log(playerName)
}
查看更多
Luminary・发光体
3楼-- · 2020-05-25 05:00
<form (submit)="onSubmit()">
   <input [(ngModel)]="playerName">
</form>

let playerName: string;
onSubmit() {
  return this.playerName;
}
查看更多
叛逆
4楼-- · 2020-05-25 05:06

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;
}
查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-05-25 05:06

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);
   }
 }
查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-05-25 05:08

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);}
查看更多
Juvenile、少年°
7楼-- · 2020-05-25 05:10

html

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

ts

@ViewChild('fondovalor') fondovalor:ElementRef;

getFotoFondo(){ 
        const valueInput = this.fondovalor.nativeElement.value
}
查看更多
登录 后发表回答