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

问题描述 投票:0回答:3

我的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">中键入的任何内容都会立即显示在{{box.value}}中。因为这纯粹是在html文件中,所以我想知道如何将输入{{box.value}}绑定到sampleString: string;中的component.ts,以便可以在其他地方使用它。

angular typescript
3个回答
0
投票

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

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

    ngOnInit(): void {}
}

0
投票

您可以在输入元素中的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>

0
投票

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

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

Working Demo

© www.soinside.com 2019 - 2024. All rights reserved.