[英]How to bind input keyup value to a variable in component.ts?
I have the following in my component.ts
file:我的
component.ts
文件中有以下内容:
@Component({
selector: 'app-loop-back',
template: `
<input #box (keyup)="0">
<p>{{box.value}}</p>
`
})
export class LoopbackComponent implements OnInit{
sampleString: string;
contructor(){}
ngOnInit(): void {}
}
Basically whatever I typed in the <input #box (keyup)="0">
will be shown immediately in the {{box.value}}
.基本上,我在
<input #box (keyup)="0">
中输入的任何内容都会立即显示在{{box.value}}
中。 As this is purely in the html file, I am wondering how can I bind the input {{box.value}}
to sampleString: string;
由于这纯粹是在 html 文件中,我想知道如何将输入
{{box.value}}
绑定到sampleString: string;
in my component.ts
so that I can use it somewhere else.在我的
component.ts
中,以便我可以在其他地方使用它。
you can bind the method on change
event in input element and update the string value您可以在输入元素中绑定
change
事件的方法并更新字符串值
class file
class 文件
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
sampleString: string;
updateBox(e) {
this.sampleString = e.target.value;
}
}
Template File
模板文件
<input #box (keyup)="0" (input)="updateBox($event)">
<p>{{box.value}}</p>
<p>This is sampleString Value: {{sampleString}} </p>
You can use angular two way binding as shown below您可以使用 angular 两种方式绑定如下图
@Component({ selector: 'app-loop-back', template: ` <input [(ngModel)]="sampleString"> <p>{{sampleString}}</p> ` }) export class LoopbackComponent implements OnInit{ sampleString: string; contructor(){} ngOnInit(): void {} }
Try like this if you want to use only HTML an not 2 way binding,如果您只想使用 HTML 而不是 2 路绑定,请尝试这样,
<input #box (keyup)="sampleString = $event.target.value">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.