angular reactive form

这篇文章讲了angular reactive form,

 

这里是angular file upload 组件 https://malcoded.com/posts/angular-file-upload-component-with-express/ 

 

原文:https://malcoded.com/posts/angular-fundamentals-reactive-forms/

------------------------------------

Forms are arguably one point where angular really shines.

So learning how forms work in angular is an essential skill.

In this tutorial we are going to take a close look at one of the two ways to create forms in angular. The reactive forms.

We will dive right into code and discover all the details about reactive forms in the angular framework step by step and with easy examples.

So, without further ado, let’s get started!

angular-forms-banner

Forms in Angular

There are two different approaches to forms in Angular.

The first category are the template-driven forms. Using this method, you first create html-input-elements and then use directives like ngModel to bind their value to a component’s variable.

Personally, I’ve used this technique a lot. But that way only because I did not know about the other category.

Reactive Forms.

Reactive Forms a kind of the opposite to template-driven forms. Instead of defining the form in your template, the structure of the form is defined in code.

This maybe sounds a little bit odd now. At least I felt like this.

“Isn’t it twice the work, to define the form in code?”

“And isn’t it much harder to read?”

That was what I asked myself and that is what you should ask yourself, too!

But please wait with that, until you read this article and fully understand the topic.

To answer these questions, let’s dive right in and just build a small example using reactive forms together!

angular-modules-banner

Importing the Module

For this example we are going to use a blank angular-cli application.

I you haven’t done so already, please go ahead and create one:

ng new [name]

As you probably know, Angular is organized in modules.

To use certain features, we first need to import the modules that contain that feature, before we can use it.

This is true for reactive forms, as well.

To use reactive forms, we need to import the ReactiveFormsModule into our parent module.

In our case, the parent module is the AppModule.

Let’s import the required module into it:

src/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],
})
class AppModule {}

angular-code-banner

Defining a Model

In this example we are going to create a simple contact-form, because I couldn’t think of something more creative.

Before we start creating our form, we first need to define, which information we would like to gather with it.

To do so, we are creating a so called model.

A model is just a class, that contains all the fields, that our data can have.

All we need to do, is to create a new file for that class. Also, I typically create a new folder called models to contain all models of the application.

Inside of that file, we create our model. In this case, the data will be split in two parts.

Personal data about the person using the contact-form and the actual data he/she wants to submit.

The model for that looks like this:

src/models/contact-request.ts
export class ContactRequest {
  personalData: PersonalData
  requestType: any = ''
  text: string = ''
}

class PersonalData {
  email: string = ''
  mobile: string = ''
  country: string = ''
}

As you can see, I have also added default values to each field, as we will require them later.

angular-new-banner

Setting up a Contact-Component

Next, we need a component, to create our form in.

So let’s just create one!

Just use the following command of the angular-cli:

ng generate component contact

This will create a basic component for us to use. It will also import that component into our AppModule automatically.

angular-animation-banner

Creating a Reactive Form in Angular

Now we can finally start creating our form.

Other than with template-driven forms, we can not simply use the model we have created earlier.

Instead we have to create a different one. One, that is only responsible for the form-representation.

But why doe we have to do that? Isn’t that much more complex that just binding to the model ?

Of course it is.

But binding to the model directly comes with one large downside.

We are altering the original data directly.

Reactive Programming and Immutability

This has become bad-practice in the last couple years, as a paradigm called reactive programming took the programming world over more and more.

Why?

Well, the simplest answer might be, that we loose the original data. If the user decides to abort his action, we can not recover the previous state, as we have overwritten it.

What we do with reactive forms instead, is keeping the data in the form model, until the user hits the submit button.

Only then the data is copied over to the original model, replacing everything. This type of overwriting everything is called “immutable objects”.

Form Controls

To create this form-model, angular uses a class called FormGroup.

To define our form-model, we create a new FormGroup. The constructor of this class then takes an object, that can contain sub-form-groups and FormControls.

FormControls represent the leafs in this tree. They are the smallest possible unit and typically represent a HTML-control (input, select, …) of your template.

In actuall code, let’s create a new method, that creates a new instance of the form-model for us. We call this mehtod: createFormGroup.

src/contact/contact.component.ts
createFormGroup() {
  return new FormGroup({
    personalData: new FormGroup({
      email: new FormControl(),
      mobile: new FormControl(),
      country: new FormControl()
     }),
    requestType: new FormControl(),
    text: new FormControl()
  });
}

You will notice the similarities with our contact-request model.

In fact, I would recommend that you always keep them that similar. That way, you wont have any trouble converting the form-model to your actual model.

Because we want the country and the request Type to be select-able as a drop-down, we also have to provide some options to choose from:

src/contact/contact.component.ts
countries = ['USA', 'Germany', 'Italy', 'France']

requestTypes = ['Claim', 'Feedback', 'Help Request']

Finally, we save the result of that method to a public field, to be accessible in our template.

src/contact/contact.component.ts
contactForm: FormGroup;
constructor() {
    this.contactForm = this.createFormGroup();
}

Here is how your component should look like now:

src/contact/contact.component.ts
import { Component, OnInit } from '@angular/core'
import { FormControl, FormGroup } from '@angular/forms'

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css'],
})
class ContactComponent implements OnInit {
  contactForm: FormGroup

  countries = ['USA', 'Germany', 'Italy', 'France']

  requestTypes = ['Claim', 'Feedback', 'Help Request']

  constructor() {
    this.contactForm = this.createFormGroup()
  }

  // Step 1
  createFormGroup() {
    return new FormGroup({
      personalData: new FormGroup({
        email: new FormControl(),
        mobile: new FormControl(),
        country: new FormControl(),
      }),
      requestType: new FormControl(),
      text: new FormControl(),
    })
  }

  ngOnInit() {}
}

angular-ui-banner

Implementing the Template

For now that is all we need to do code-wise.

Let’s take a look how the counterpart, the template will look like.

Basically, our HTML does look just like a regular form. The only difference is, that we have to tell angular, which FormGroup and which FormControl to use for each control.

To see the result, I’ve also added a paragraph to print out our form-model as json.

src/contact/contact.component.html
<form [formGroup]="contactForm" (ngSubmit)="onSubmit()" novalidate>
  <div formGroupName="personalData" novalidate>
    <input formControlName="email" /> <input formControlName="mobile" />
    <select formControlName="country">
      <option *ngFor="let country of countries" [value]="country"
        >{{country}}</option
      >
    </select>
  </div>
  <select formControlName="requestType">
    <option *ngFor="let requestType of requestTypes" [value]="requestType"
      >{{requestType}}</option
    >
  </select>
  <input formControlName="text" />
  <button type="submit" [disabled]="contactForm.pristine">Save</button>
  <button type="reset" (click)="revert()" [disabled]="contactForm.pristine">
    Revert
  </button>
</form>

At this point, your app should be in a runable state again.

In case you didn’t know: You can start your application using the

ng serve

command.

angular-build-banner

Using the Angular Form-Builder

From the example of our TypeScript code above, we can say that the code is starting to look cluttered already.

To solve that, angular provides a service called FormBuilder. This FormBuilder allows us to build our form-model with less code.

To use the FormBuilder, we need to request it via dependency injection. We do so in the constructor of our component.

src/contact/contact.component.ts
constructor(private formBuilder: FormBuilder) {
    this.contactForm = this.createFormGroup();
}

The FormBuilder class has to be imported from @angular/forms:

src/contact/contact.component.ts
import { FormControl, FormGroup, FormBuilder } from '@angular/forms'

Now we can use that FromBuilder to build our form-model. For demonstration-purposes, I have created a new method called “createFormGroupWithBuilder”. You can just replace you previous code if you want to.

src/contact/contact.component.ts
createFormGroupWithBuilder(formBuilder: FormBuilder) {
    return formBuilder.group({
      personalData: formBuilder.group({
        email: 'defaul@email.com',
        mobile: '',
        country: ''
      }),
      requestType: '',
      text: ''
    });
  }

Using this approach, we have to define the default values of each field. You can just pass them an empty string, or fill it with some default-data as I did with the “email”-field.

Passing a Class to the Form-Builder

I turns out, using the FormBuilder, we can further optimize our code.

Instead of defining our form-model inline, the FormBuilder allows us to pass in any JavaScript object.

So we can just pass in a new instance of our PersonalData class.

src/contact/contact.component.ts
createFormGroupWithBuilderAndModel(formBuilder: FormBuilder) {
    return formBuilder.group({
      personalData: formBuilder.group(new PersonalData()),
      requestType: '',
      text: ''
    });
  }

However, we have to make sure, that all fields of the form are also present in this object. This is why we have assigned the default values in our contact-request-model.

angular-test-banner

Extracting the Data from the Form

Now that have talked about our more than enough, it’s time to worry about getting our data out of that form into an contact-request object.

For that, we are using the submit-button, we have created earlier in our template. We also already registered the callback-method “onSubmit”.

To be able to listen to the button-press, we need to implement that callback in our component.

Inside of that callback, we can access the form’s values by its values property.

this.contactForm.value

But we need to be careful here. These values are still referenced by our form. If we just copy that reference and modify the data elsewhere, the form will be impacted, as well. This can cause weird side-effects.

This is why we need to create a copy of the data. In this example we are using Object.assign for that.

const result: ContactRequest = Object.assign({}, this.contactForm.value);

However, that is not enough. Object.assign creates something called a shallow copy. That means that all primary-fields of the object are copied properly, but the references to sub-objects or lists are still the same. Not noticing this problem does cause even more weird side-effects.

Instead what we want to do is create a deep copy. We can either achieve that by doing it copying everything manually or use a utility like lodash’s cloneDeep function. We will use the manual method here.

result.personalData = Object.assign({}, result.personalData);

Overall, the onSubmit method should now look something like this:

src/contact/contact.component.ts
onSubmit() {
    // Make sure to create a deep copy of the form-model
    const result: ContactRequest = Object.assign({}, this.contactForm.value);
    result.personalData = Object.assign({}, result.personalData);

    // Do useful stuff with the gathered data
    console.log(result);
  }

angular-healing-banner

Resetting the Form

Resetting the form is definitely one of the easier parts with reactive forms.

Again, we are going to use the reset-button, we have included into our template already.

All we need to do now, is to implement the revert-callback into our component.

To reset the form, we can either use the form’s reset method without any parameter,

// Resets to blank object
this.contactForm.reset();

which results in an empty object, or pass a set of default parameters along:

// Resets to provided model
this.contactForm.reset({ personalData: new PersonalData(), requestType: '', text: '' });

All in all the revert method simply looks like this:

src/contact/contact.component.ts
revert() {
    // Resets to blank object
    this.contactForm.reset();

    // Resets to provided model
    this.contactForm.reset({ personalData: new PersonalData(), requestType: '', text: '' });
  }

Conclusion

In this tutorial we learned how to create forms with angular using the reactive-forms method.

I hope you enjoyed this post.

If you did please hit the share button below and help other people understand reactive-forms in angular, as well.

Have a fantastic day!

原文地址:https://www.cnblogs.com/oxspirt/p/10863863.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中文文档更容易理解,前提是你的英语基础还可以。英文文档对于知识点讲述简明扼要,通俗易懂,而有些中文文档读起来特别费力,基础差、底子薄的有可能一会就会被绕晕了,最起码英文文档中的代码与中文文档中的代码是一致的,但知识点讲述实在是差距太大。Angular.jshasapowerfuldire
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是一个令人印象深刻的 JavaScript 图表库,建立在 HTML5 Canvas 基础上。目前,它支持6种图表类型(折线图,条形图,雷达图,饼图,柱状图和极地区域区)。而且,这是一个独立的包,不依赖第三方 JavaScript 库,小于 5KB。   其中用到的软件:   Chart.js框架,版本1.0.2,一
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,结局方案为更换jquery、angularjs、IE的版本。 1.首先尝试更换jquery版本为1.7.2 jquery-1.9.1.js-->jquery-1.7.2.js--> jquery2.1.4.js 无效 2.尝试更换IE版本IE8 IE11-
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:http://ngmodules.org/modules/angularjs-dropdown-multiselecthttp://dotansimha.github.io/angularjs-dropdown-multiselect/#/AngularJSDropdownMultiselectThisdire
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目需求,需要在首页搜索框中添加语音输入功能,考虑到科大讯飞语音业务的强大能力,遂决定使用科大讯飞语音输入第三方服务。软件首页截图如下所示: 涉及的源代码如下所示: //语音识别$rootScope.startRecognize = function() {var speech;
Angular数据更新不及时问题探讨前言 在修复控制角标正确变化过程中,发觉前端代码组织层次出现了严重问题。传递和共享数据时自己使用的是rootScope,为此造成了全局变量空间的污染。根据《AngularJs深度剖析与最佳实践》,如果两个控制器的协作存在大量的数据共享和交互可以利用Factory等服务的“单例”特性为它们注入一个共享对象来传递数据。而自己在使用rootScope
HTML:让表单、文本框只读,不可编辑的方法有时候,我们希望表单中的文本框是只读的,让用户不能修改其中的信息,如使中国">的内容,"中国"两个字不可以修改。实现的方式归纳一下,有如下几种。方法1:onfocus=this.blur()中国"onfocus=this.blur()>方法2:readonly中国"readonly>中国"readonly="tru
在AngularJS应用中实现微信认证授权遇到的坑前言 项目开发过程中,移动端新近增加了一个功能“微信授权登录”,由于自己不是负责移动端开发的,但最后他人负责的部分未达到预期效果。不能准确实现微信授权登录。最后还得靠自己做进一步的优化工作,谁让自己是负责人呢?原来负责人就是负责最后把所有的BUG解决掉。 首先,熟悉一下微信授权部分的源代码,如下所示:
AngularJS实现二维码信息的集成思路需求 实现生成的二维码包含订单详情信息。思路获取的内容数据如下: 现在可以获取到第一级数据,第二级数据data获取不到。利用第一级数据的获取方法获取不到第二级数据。for(i in data){alert(i); //获得属性 if(typeof(data[i]) == "o
Cookie'data'possiblynotsetoroverflowedbecauseitwastoolarge(5287>4096bytes)!故事起源 项目开发过程中遇到以上问题,刚开始以为只是个警告,没太在意。后来发现直接影响到了程序的执行效果。果断寻找解决方法。问题分析 根据Chrome浏览器信息定位,显示以下代码存在错误:
AngularJS控制器controller之间如何通信angular控制器通信的方式有三种:1,利用作用域继承的方式。即子控制器继承父控制器中的内容2,基于事件的方式。即$on,$emit,$boardcast这三种方式3,服务方式。写一个服务的单例然后通过注入来使用利用作用域的继承方式由于作用域的继承是基于js的原型继承方式,所以这里分为两种情况,当作用域上面的值
AngularJS路由问题解决遇到了一个棘手的问题:点击优惠详情时总是跳转到药店详情页面中去。再加一层地址解决了,但是后来发现问题还是来了:Couldnotresolve'yhDtlMaintain/yhdetail'fromstate'yhMaintain'药店详情http://192.168.1.118:8088/lmapp/index.html#/0优惠券详情
书海拾贝之特殊的ng-src和ng-href在说明这两个指令的特殊之前,需要先了解一下ng的启动及执行过程,如下:1)浏览器加载静态HTML文件并解析为DOM;2)浏览器加载angular.js文件;3)angular监听DOMContentLoaded事件,监听到时开始启动;4)angular寻找ng-app指令,确定作用范围;
angularjs实现页面跳转并进行参数传递Angular页面传参有多种办法,我在此列举4种最常见的:1.基于ui-router的页面跳转传参(1)在AngularJS的app.js中用ui-router定义路由,比如现在有两个页面,一个页面(producers.html)放置了多个producers,点击其中一个目标,页面跳转到对应的producer页,同时将producerId
AngularJS实现表格数据的编辑,更新和删除效果实现首先,我们先建立一些数据,当然你可以从你任何地方读出你的数据var app = angular.module('plunker', ['ui.bootstrap']);app.controller('MainCtrl', function($scope) { $scope.name = 'World'; $sc
ANGULAR三宗罪之版本陷阱      坑!碰到个大坑,前面由于绑定日期时将angular版本换为angular-1.3.0-beta.1时,后来午睡后,登录系统,发现无论如何都登陆不进去了,经过调试,发现数据视图已经无法实现双向绑定了。自己还以为又碰到了“僵尸程序”了呢,对比药店端的程序发现并没有什么不同之处。后来自己经过一番思索才隐约感觉到是不是angular的版本造成的,将版本换为之前
JS实现分页操作前言 项目开发过程中,进行查询操作时有可能会检索出大量的满足条件的查询结果。在一页中显示全部查询结果会降低用户的体验感,故需要实现分页显示效果。受前面“JS实现时间选择插件”的启发,自己首先需要查看一下HTML5能否实现此效果。 整了半天,不管是用纯CSS3也好,还是用tmpagination.js还是bootstrap组件也好,到最后自己静下心来理
浏览器兼容性解决之道前言 浏览器兼容性一直是前端开发中不得不面对的一个问题。而最突出的就是IE。对绝大多数公司来说,兼容IE6的性价比已经很低,而IE7则几乎已经绝迹。所以,常见的兼容性下限是IE8。这也正是Angular1.2x的兼容性目标,Angular团队声明:Angular的持续集成服务器会在IE8下运行所有的测试。但这些测试不会运行在IE7及以下版本,它们也不会保证An
JS利用正则表达式校验手机号绪 由于项目需求,需要在前端实现手机号码的校验。当然了,对于基本的格式校验应该放在客户端进行,而不需要再将待校验的手机号发送至服务端,在服务端完成校验,然后将校验结果返回给客户端,客户端根据返回的结果再进行进一步的处理。如此反而复杂化了处理过程。 其实,处于安全考虑,应该在服务端进行二次校验。以下为在客户端的JS中校验手机号码格式
基于项目实例解析ng启动加载过程前言 在AngularJS项目开发过程中,自己将遇到的问题进行了整理。回过头来总结一下angular的启动过程。 下面以实际项目为例进行简要讲解。1.载入ng库2.等待,直到DOM树构造完毕。3.发现ng-app,自动进入启动引导阶段。4.根据ng-app名称找到相应的路由。5.加载默认地址。6.Js顺序执行,加载相应模版页sys_tpls/