如何将输入的keyup值绑定到component.ts中的变量?

时间:2019-11-01 03:39:10

标签: angular typescript

我的structure(list(ID = c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"), start = c(25, 36, 23, 15, 21, 43, 39, 27, 11, 21, 28, 44, 16, 25), end = c(67, 97, 85, 67, 52, 72, 55, 62, 99, 89, 65, 58, 77, 88), sampled = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, -14L), spec = structure(list( cols = list(ID = structure(list(), class = c("collector_character", "collector")), start = structure(list(), class = c("collector_double", "collector")), end = structure(list(), class = c("collector_double", "collector")), sampled = structure(list(), class = c("collector_logical", "collector"))), default = structure(list(), class = c("collector_guess", "collector")), skip = 1), class = "col_spec"))``` 文件中包含以下内容:

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 {} } 中键入的任何内容都会立即显示在<input #box (keyup)="0">中。由于这完全是html文件中的内容,我想知道如何将输入{{box.value}}绑定到{{box.value}}中的sampleString: string;上,以便可以在其他地方使用它。

3 个答案:

答案 0 :(得分:2)

您可以在输入元素中的change事件上绑定方法并更新字符串值

  

课程文件

    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; 
       }

    }
  

模板文件

<input #box (keyup)="0" (input)="updateBox($event)">
  <p>{{box.value}}</p>
<p>This is sampleString Value: {{sampleString}} </p>

答案 1 :(得分:1)

您可以使用如下所示的角度双向绑定

@Component({
  selector: 'app-loop-back',
  template: `
    <input [(ngModel)]="sampleString">
    <p>{{sampleString}}</p>
  `
})
export class LoopbackComponent implements OnInit{ 
    sampleString: string;
   contructor(){}

    ngOnInit(): void {}
}

答案 2 :(得分:0)

如果您只想使用HTML而不是2种方式的绑定,请尝试这样

<input #box (keyup)="sampleString = $event.target.value">

Working Demo