【问题标题】:Angular on keyup.enter send the current text of an input to a methodAngular on keyup.enter 将输入的当前文本发送到方法
【发布时间】:2019-01-24 19:09:15
【问题描述】:

我有一个输入,我想获取它当前得到的文本并将其发送到一个方法。

代码如下:

app.component.html

<input type="text" (keyup.enter)="sendit()" />

app.component.ts

sendit() {
    console.log(The text in the input);
}

我该怎么做?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    你可以像下面那样做,

    <input type="text" (keyup.enter)="sendit($event.target.value)" />
    
     sendit(data){
        console.log("Value",data)
     }
    

    这里使用双向绑定是一种解决方案,

    how to get value from textbox using typescript in angular 2

    希望对你有帮助。

    谢谢,

    穆图

    【讨论】:

      【解决方案2】:

      有多种方法可以做到这一点:

      input 使用模板变量。你会像这样得到它的value

      <input #yourInput type="text" (keyup.enter)="sendit(yourInput.value)" />
      

      在 Component 中,得到它是这样的:

      sendit(inputValue) {
        console.log(inputValue);
      }
      

      或者,您也可以使用[(ngModel)] 两种方式绑定文本字段:

      <input 
        type="text" 
        [(ngModel)]="bindedTwoWays"
        (keyup.enter)="sendit(bindedTwoWays)" >
      

      在组件中:

      import { Component } from '@angular/core';
      
      @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
      })
      export class AppComponent {
        bindedTwoWays = 'Angular';
      
        sendit(inputValue) {
          console.log(inputValue);
        }
      }
      

      这是一个Working Sample StackBlitz,其中包含两种方法供您参考。

      【讨论】:

        【解决方案3】:

        input 元素创建一个模板变量并像这样传递您的输入值

        <input #inp type="text" (keyup.enter)="sendit(inp.value)" />
               ^^^^                                   ^^^^^^^^^
        

        接受方式

        sendit(inputValue) {
            console.log(inputValue);
        }
        

        【讨论】:

          猜你喜欢
          • 2016-12-08
          • 2020-04-11
          • 1970-01-01
          • 1970-01-01
          • 2021-06-11
          • 2021-02-25
          • 2021-07-03
          • 2015-09-23
          • 1970-01-01
          相关资源
          最近更新 更多