Angular FormControl:如何在Angular 13中使用FormControl

482 阅读7分钟

Angular FormControl Example | Angular 8 FormControl

Angular FormControl是一个内置的类,用于获取和设置值并验证表单控件字段,如或。FormControl跟踪单个表单控件的值和验证状态。它可以独立使用,也可以与父表单一起使用。 Angular表单的类型 在Angular中有两种类型的表单方法。 反应式表单(ReactiveForms 模板驱动的表单 反应式表单 使用FormControl、FormGroup和FormArray创建的表单被说成是反应式表单。因此,它们使用ng模块作为ReactiveFormsModule。 FormControl: FormControl是用于获取和设置表单控件的值和验证的类,如和标签。 表单组。 FormGroup的作用是跟踪一组FormControl的值和有效性状态。 FormArray: FormArray跟踪FormControl、FormGroup或FormArray实例阵列的值和有效性状态。 模板驱动的表单 模板驱动的表单只是模型驱动的表单,由模板中的指令与组件中的代码驱动。 在模板驱动中,我们使用指令来创建模型。在模型驱动中,我们在组件上生成一个模型,然后使用指令将模板中的元素映射到我们的表单模型。 Angular FormControl FormControl是Angular表单的三个基本构件之一,另外还有FormGroup和FormArray。它扩展了AbstractControl类,实现了访问值、验证状态、用户交互和事件的大部分基本功能。 如果你对FormControl、FormGroup、FormArray和Validators类感到困惑,这篇文章将帮助你了解它们如何共同构建优秀的angular表单。 对于每个表单控件,如文本、复选框或单选按钮,我们需要在我们的类中创建FormControl的实例。 例如,假设我们需要创建一个name 字段的实例。 name = new FormControl(); 在我们的HTML模板中,你可以使用以下代码。 <input [formControl]="name"> 好的,让我们举一个基本的例子。 首先,创建一个新的angular项目。 然后在app.module.ts 文件中导入ReactiveFormsModule。 // app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } 所以,我们已经导入了ReactiveFormsModule,并在import数组中添加。 下一步是在app.component.ts 文件中编写以下代码。 // app.component.ts import { Component } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { name = new FormControl('', [Validators.required]); } 我们在app.component.ts 文件中导入了FormControl和Validators 类,并创建了一个名为name的FormControl实例**。** 这意味着现在我们从HTML表单中追踪名字字段。 在app.component.html文件中写下以下代码。 <!-- app.component.html --> <div> <input [formControl]="name"> <label *ngIf="name.invalid" [ngClass] = "'error'"> Name is required </label> </div> 另外,我们有一个条件,说如果名字字段无效,它将显示错误。 在我们的例子中,如果它是空的,它将显示错误,如果它不是,它将消失。 另外,在app.component.css 文件中写下以下代码。 .error{ color: red; font-size: 15px; } 保存该文件并运行以下命令来启动angular dev服务器。 ng serve -o 你会看到类似下面的内容。 当你开始输入名字时,错误会消失。 在FormControl中设置默认值 我们可以给我们的表单控件设置一个默认值,在我们的类中实例化一个表单控件时绕过这个值。在app.component.ts 文件中更新以下代码。 // app.component.ts name = new FormControl('The Weeknd', [Validators.required]); 保存文件,你会看到文本框中填入 "The Weeknd"。 获取FormControl中的值。 我们可以通过使用类中FormControl实例的value属性来获取FormControl的值。但是,首先,在app.component.ts 文件中更新以下代码。 // app.component.ts import { Component, OnInit } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { name = new FormControl('The Weeknd', [Validators.required]); ngOnInit() { console.log(this.name.value); } } 保存该文件,在浏览器的控制台标签里面,你会看到The Weeknd 被记录下来。 所以value属性获取的是FormControl这个名字的值。 在FormControl中设置值 如果用户在用户界面中输入了新的值,我们的FormControl实例将被更新为新的值。 现在要在运行时给FormControl设置一个值,我们需要在类中的FormControl实例上调用setValue()方法。 在app.component.ts 文件中写下以下代码。 // app.component.ts import { Component } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { name = new FormControl('The Weeknd', [Validators.required]); setNameValue() { this.name.setValue('Ankit'); } } 在这段代码中,我们定义了setNameValue() 函数,当用户在按钮上发射事件(如onchange或click事件)时,它将设置值Ankit。 我们正在使用一个按钮,所以我们也需要更新app.component.html文件。 <!-- app.component.html --> <div> <input [formControl]="name"> <label *ngIf="name.invalid" [ngClass] = "'error'"> Name is required </label> <div> <button (click)="setNameValue()">Set value</button> </div> </div> 保存该文件,现在,当你点击设置值按钮时,你将看到文本框内的**'Ankit'** 。 使用FormControlName的FormGroup的FormControl FormGroup跟踪一组FormControl实例的值和有效性状态。FormGroup是Angular中用来定义表单的三个基本构件之一,此外还有FormControl和FormArray。 FormGroup将每个子FormControl的值聚集到一个对象中,每个控件的名称是一个键。它通过减少其子女的状态值来计算其状态。 例如,如果一个组中的一个控件是无效的,整个组就会变成无效的。因此,当实例化一个表单组时,传入一个子控件的集合作为第一个参数。每个子控件的关键是注册该控件的名称。 让我们再添加两个字段。在app.component.ts 文件中写下以下代码。 // app.component.ts import { Component } from '@angular/core'; import { FormControl, Validators, FormGroup } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { angForm = new FormGroup({ name: new FormControl('Krunal', Validators.maxLength(10)), age: new FormControl(26, Validators.required), college: new FormControl('VVP College'), }); onFormSubmit(): void { console.log('Name:' + this.angForm.get('name').value); console.log('Age:' + this.angForm.get('age').value); console.log('College:' + this.angForm.get('college').value); } } 首先,我们从Angular forms中导入了FormGroup 模块,创建了FormGroup的实例,传递了所有三个字段,并创建了其FormControl实例。 在类中创建的FormControl实例已经在HTML中使用了angular formControlName ,它将FormControl的值与HTML表单控件同步。 formGroup]是FormGroupDirective,它将现有的FormGroup绑定到一个DOM元素。 当表单被提交时,我们可以按如下方式访问表单值。 this.angForm.get('name').value 因此,当用户提交表单时,我们将在控制台日志里面获得所有三个表单字段的值。 使用FormGroup的Angular FormControl验证 在app.component.html 文件中写下以下代码。 // app.component.ts import { Component } from '@angular/core'; import { FormControl, Validators, FormGroup } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { angForm = new FormGroup({ name: new FormControl('', Validators.required), age: new FormControl('', Validators.required), college: new FormControl('', Validators.required), }); get name(): any { return this.angForm.get('name'); } get age(): any { return this.angForm.get('age'); } get college(): any { return this.angForm.get('college'); } onFormSubmit(): void { console.log('Name:' + this.angForm.get('name').value); console.log('Age:' + this.angForm.get('age').value); console.log('College:' + this.angForm.get('college').value); } } 为了验证一个特定的表单控件,我们需要获得该表单控件的值。 例如,为了验证姓名、年龄和大学的FormControl,我们需要在我们的类中创建一个方法,如上所述。 get name(): any { return this.angForm.get('name'); } get age(): any { return this.angForm.get('age'); } get college(): any { return this.angForm.get('college'); } 现在,在app.component.html 文件中写下以下代码。 <!-- app.component.html --> <form [formGroup] = "angForm" (ngSubmit)="onFormSubmit()"> <input formControlName="name" /> <label *ngIf="name.invalid" [ngClass] = "'error'"> Name is required. </label> <input formControlName="age" /> <label *ngIf="age.invalid" [ngClass] = "'error'"> Age is required. </label> <input formControlName="college" /> <label *ngIf="college.invalid" [ngClass] = "'error'"> College is required. </label> <div> <button type="submit">Send</button> </div> </form> 所以,现在在***ngif条件下,** 我们可以直接使用该函数名称作为对象名称进行访问,并调用该对象的各种属性,如无效、有效、待定、原始、肮脏、未触及或触及。 保存文件并进入浏览器,你会看到这样的东西。 带有FormArray和FormControlName的表单控件 在本节中,我们将使用FormArray的FormControl和使用FormControlName的FormGroup。 在我们的angular应用程序中,FormArray被用来动态生成表单控件,如和。 在app.component.ts 文件中定义名称FormArray。 // app.component.ts import { FormControl, FormGroup, FormArray, Validators } from '@angular/forms'; get names(): FormArray { return this.angForm.get('names') as FormArray; } 接下来,我们需要使用FormGroup聚合来命名FormArray。在app.component.ts 文件中写下以下代码来完成这个任务。 // app.component.ts angForm = new FormGroup({ names: new FormArray([ new FormControl('', Validators.required), new FormControl('', Validators.required), ]) }); 在上面的代码中,我们已经创建了一个FormControl实例的数组。 我们将在我们的用户界面中迭代它。在app.component.html 文件中写下以下代码。 <div formArrayName="names"> <div *ngFor="let name of names.controls; index as idx"> <input [formControlName]="idx" placeholder="Enter a Name"> <label *ngIf="name.invalid" [ngClass] = "'error'"> Name is required. </label> </div> </div> 当我们提交表单时,我们可以按照下面的方法获取值。 在app.component.ts 文件中写下以下代码。 // app.component.ts onFormSubmit(): void { for(let i = 0; i < this.names.length; i++) { console.log(this.names.at(i).value); } } 在FormArray的实例上,即名字,我们将调用控件,返回FormControl实例的数组。 为了在运行时添加一个表单控件,我们需要使用FormArray的push()方法。 在创建FormControl实例的同时,我们也在添加验证。 // app.component.ts addNameField() { this.names.push(new FormControl('', Validators.required)); } 我们可以在运行时移除表单控件;我们需要使用FormArray的removeAt()方法。 // app.component.ts deleteNameField(index: number) { this.names.removeAt(index); } 所以,我们的app.component.ts文件看起来像这样。 // app.component.ts import { Component } from '@angular/core'; import { FormControl, FormGroup, FormArray, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { angForm = new FormGroup({ names: new FormArray([ new FormControl('', Validators.required), new FormControl('', Validators.required), ]) }); get names(): FormArray { return this.angForm.get('names') as FormArray; } addNameField() { this.names.push(new FormControl('', Validators.required)); } deleteNameField(index: number) { this.names.removeAt(index); } onFormSubmit(): void { for(let i = 0; i < this.names.length; i++) { console.log(this.names.at(i).value); } } } 现在,在app.component.html 文件中写下我们的最终代码。 <!-- app.component.html --> <form [formGroup] = "angForm" (ngSubmit)="onFormSubmit()"> <div formArrayName="names"> <div *ngFor="let name of names.controls; index as idx"> <input [formControlName]="idx" placeholder="Enter a Name"> <label *ngIf="name.invalid" [ngClass] = "'error'"> Name is required. </label> <button (click)="deleteNameField(idx)">Delete</button> </div> </div> <div> <button type="submit">Send</button> <button type="button" (click)="addNameField()">Add More Names</button> </div> </form> 保存该文件,你会看到以下内容。 现在,当你开始在一个特定的文本框中输入你的名字时,对于那个特定的文本框,错误会消失。 当用户提交表单时,我们会得到所有动态添加的文本框值。 结论 Angular FormControl 类跟踪和控制表单字段的值。它可以设置和获取值。使用FormArray,你可以尽可能多地添加动态字段,在Angular 13中变得毫不费力。 你可以在Angular文档中找到更多关于FormControl的信息。 本教程就到此为止。 The postAngular FormControl: How to Use FormControl in Angular 13appeared first onAppDividend.