在Angular|Typescript中获取输入文本值的6种方法

1,102 阅读5分钟

在Angular应用程序中,表单是一个基本的UI元素,显示在浏览器页面上以接受用户信息。表单包含多个html输入元素来接受用户的输入。按钮允许用户将信息提交给后台API,并调用点击绑定事件。

在Angular中,视图是html模板,控制器是一个类型化的组件。

读取输入文本是每个Angular开发者都需要知道的基本概念。

这篇文章涵盖了multiple ways to read input value in Angular application 。以下是不同的方法

使用ngModel指令的双向数据绑定

two-way data binding 是一个重要的内置功能,从angular 2版本开始引入。

它对于从componenttemplate 的数据共享是非常有用的,反之亦然。

这些绑定使父子之间的沟通更容易。

  • 在单向绑定中,运行事件听从表单中的输入并准备传递给组件。
  • 一旦组件改变其值,就更新表单的输入值。

下面是一个关于reading the input text value on button click 的例子。

首先,在AppModule文件中导入FormModule ,以进行双向绑定。

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

在组件模板html文件中,

在输入字段中添加ngModel ,如例子中给出的。

为输入元素添加了ngModel指令。


 {{username}}

Clickme

在组件的 typescript 文件中,声明一个类型为string

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  username: string = '';
  clickme() {
    console.log('it does nothing',username);
  }
}

与本地引用对象的单向绑定

在组件的HTML模板中,为输入框添加了hash(#)本地引用。这个引用持有一个类型为HTMLInputElement 的对象。

在按钮的点击事件中使用'HTMLInputElement .value'传递输入的本地引用对象的值。


 {{username}}

Clickme

创建了一个方法clickme 来捕捉组件中的点击事件,该方法接受字符串参数。

这是另一种读取输入文本值的方法

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  clickme(username:string) {
    console.log('it does nothing',username);
  }
}

带本地引用的viewchild 2方式绑定

首先,在html模板视图中定义一个输入文本元素的本地引用

在控制器中,在组件中声明viewChild ,它是对输入元素的引用。

  @ViewChild('username', {static: true}) usernameElement: ElementRef;
  myusername:string="";
  constructor(usernameElement: ElementRef){
    this.usernameElement=usernameElement;
    
  }

对于小于8的Angular版本,viewChild在组件中被注释为ElementRef 类型,以读取输入值。

@ViewChild('username') usernameElement: ElementRef;

最后,使用ElementRef.nativeElement.value 读取输入值。

以下是完整的HTML模板代码


Angular Read input value

 {{myusername}}
Clickme

控制器typescript组件在点击按钮时读取输入元素的值。

import { Component, ElementRef, ViewChild } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  @ViewChild('username', { static: true }) usernameElement: ElementRef;
  myusername: string = "";
  constructor(usernameElement: ElementRef) {
    this.usernameElement = usernameElement;

  }

  clickme() {
    this.myusername = this.usernameElement.nativeElement.value;
    console.log('it does nothing', this.myusername);
  }
}

在typescript中读取输入值

这里讲的是如何在typescript中读取输入文本的值。

首先声明输入元素如下

在typescript组件代码中,使用本地html API,document.getElementById 返回HTMLInputElement和返回值属性。getElementById ,在javascript中用id选择器选择html元素

this.myusername = (document.getElementById("username")).value;

formControlName用于在点击按钮时读取输入文本元素

formControlName 是 中的一个功能。[ReactiveFormsModule](#https://angular.io/api/forms/ReactiveFormsModule)

你必须在app.module.ts 中导入ReactiveFormsModule 模块并在导入部分添加这些模块,如下所述。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

以下是制作反应式表单的步骤

  • 在输入元素中添加formControlName

  • 添加带有formGroup名称值的表单


   
   

 
 Here is the complete html code

```html

Angular Read input value


   
   

Clickme
 {{myusername}}

在typescript控制器代码中。

  • 声明FormGroup 类型的公共变量,与html中的formGroup值相匹配。
  • 在构造函数中初始化formgroup ,使用FormBuilder
  • 使用this.nameForm.get('name') 语法进行检索
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { AbstractControl, FormBuilder, FormControl, FormGroup } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  public nameForm:FormGroup;
  myusername: string = "";
  constructor( private formBuilder: FormBuilder) {
    this.nameForm = this.formBuilder.group({
      name: ''
    });
  }
  clickme() {
    this.myusername=this.nameForm.get('name')?.value;
    console.log('it does nothing', this.nameForm.get('name'));
  }
}

输入原生事件读取值

默认情况下,html输入元素提供了本地事件,Angular也支持这些事件来读取控制器中的输入文本元素。我们可以使用以下事件

  • onBlur 事件:客户端从输入元素离开

  • onChange:当输入元素的值改变时被触发

  • input 事件:当用户输入数据时被触发

  • key 事件:当按键被输入时被触发,同时我们还有keyUp和keyDown事件

    下面是一个Angular onblur event example to read input element.

    html组件

  
Angular Read input value

    

    
 {{myusername}}

控制器组件

  import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { AbstractControl, FormBuilder, FormControl, FormGroup } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {

  myusername: string = "";

  blurEvent(event: any){
    this.myusername = event.target.value;

  }

}

Angular输入表单错误

以下是在Angular应用程序中处理表单输入文本字段时发生的错误

不能绑定到'ngModel',因为它不是'input'的已知属性。

这是在输入元素中使用ngModel集成的2路数据绑定过程中常见的错误。

解决方法是,请将FormsModule 模块导入到应用程序模块中。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

错误NG8002:不能绑定到'formGroup',因为它不是'form'的一个已知属性。

在表单处理过程中,如果你在应用程序中使用任何formControl和form group指令,会发生以下错误。

Can't bind to 'formGroup' since it isn't a known property of 'form'The solution for this error is to importReactiveFormsModule` in your application and add this module in section of application module.

import ReactiveFormsModule from @angular/forms 

总结

你学到了在Angular应用程序中读取输入表单字段的不同方法。它包括错误和它们的解决方案与例子。