Dan*_*anu 28 components input angular
我想知道如何从角度4的输入中获取值.我查看了有关角度的文档,关键事件的示例对我来说效果不好,我找不到合适的示例如何这样做,请帮助我
问题:我尝试读取输入的值,然后将值提交给另一个组件,该组件将值添加到选择标记(例如,将人员的姓名发送到选择标记的列表)
yal*_*esh 24
<form (submit)="onSubmit()">
<input [(ngModel)]="playerName">
</form>
let playerName: string;
onSubmit() {
return this.playerName;
}
Run Code Online (Sandbox Code Playgroud)
小智 17
在HTML中添加
<input (keyup)="onKey($event)">
Run Code Online (Sandbox Code Playgroud)
并在组件添加
onKey(event) {const inputValue = event.target.value;}
Run Code Online (Sandbox Code Playgroud)
Mar*_* M. 11
如果你不想使用双向数据绑定.你可以这样做.
在HTML中
<form (ngSubmit)="onSubmit($event)">
<input name="player" value="Name">
</form>
Run Code Online (Sandbox Code Playgroud)
在组件中
onSubmit(event: any) {
return event.target.player.value;
}
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用模板引用变量
<form (submit)="onSubmit(player.value)">
<input #player placeholder="player name">
</form>
Run Code Online (Sandbox Code Playgroud)
onSubmit(playerName: string) {
console.log(playerName)
}
Run Code Online (Sandbox Code Playgroud)
您可以使用(keyup)或(change)事件,请参见下面的示例:
在 HTML 中:
<input (keyup)="change($event)">
Run Code Online (Sandbox Code Playgroud)
或者
<input (change)="change($event)">
Run Code Online (Sandbox Code Playgroud)
在组件中:
change(event) {console.log(event.target.value);}
Run Code Online (Sandbox Code Playgroud)
小智 6
如果您只想读取一个字段值,我认为使用模板引用变量是最简单的方法
模板
<input #phone placeholder="phone number" />
<input type="button" value="Call" (click)="callPhone(phone.value)" />
**Component**
callPhone(phone): void
{
console.log(phone);
}
Run Code Online (Sandbox Code Playgroud)
如果您有多个字段,使用反应式表单是最好的方法之一。
小智 5
html
<input type="hidden" #fondovalor value="valores">
<button (click)="getFotoFondo()">Obtener</button>
Run Code Online (Sandbox Code Playgroud)
ts
@ViewChild('fondovalor') fondovalor:ElementRef;
getFotoFondo(){
const valueInput = this.fondovalor.nativeElement.value
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
97665 次 |
| 最近记录: |