Angular2 Response Form and angular2 response

Source: Internet
Author: User
Tags control label export class

Angular2 Response Form and angular2 response

This article provides a semi-translated semi-Summary of another non-translated advanced tutorial page on the ng2 official website.

The purpose of this article is to use the responsive form technology provided by ng2 to quickly build a rich array of interface form components.

Responsive form is a responsive ng2 technology. This article will explain the responsive form and use it to create a hero details editor.

Content:

  1. Introduction to responsive forms
  2. Start building
  3. Create a data model
  4. Create a responsive form component
  5. Create a created Template File
  6. Introduce ReactiveFormsModule
  7. Show HeroDetailComponent
  8. Add a FormGroup
  9. Look at the Form Model
  10. Introduction to FormBuilder
  11. Verification requirements
  12. Place FormGroup
  13. Check FormControl attributes
  14. Set form model data using setValue and patchValue
  15. Use FotmArray to provide an array of FormGroup
  16. Observe control changes

Introduction to responsive forms

Angular provides two forms building technologies: responsive forms and template-driven forms. All rely on the @ angular/forms library and share some common form control sets.
However, they have different principles, code styles, and technologies. They even have their own modules: ReactiveFormsModule and FormsModule.

Response Form (ReactiveFormsModule ):

Anguar response forms simplify the implementation of responsive encoding when managing data, and use a data model without a view (obtained from the server) A view-oriented model is used to maintain the value and status displayed by the HTML control on the screen. The response form provides the convenience of testing and verifying the response mode.

Using responsive forms, you will create an anular Form Control tree object in the component class and bind it to the native form control label using the provided technology in the component template.

You can directly create and operate control objects in the component class. Because the component class can directly access the data model and form control structure, you can push the data model value to the Form Control and respond to user changes to the back. The widget can observe changes in the form control status and respond to these changes.

One advantage of using form control objects directly is that values and verification Updates can always be synchronized and controlled by you. You will not encounter time problems sometimes caused by template-driven forms, and responsive forms are easier to test.

To maintain response consistency, the component saves inconsistent data models and regards them as pure original values. Without directly updating the data model, the component will extract user changes and forward them to external components or services (which may be used to save them) and return a new data model to the component, it is used to respond to model status updates.

Using responsive form commands does not require you to rely on the full response principle, but it does promote responsive programming methods if you choose to use this method.

Template-driven form (FormsModule ):

Template-driven forms use completely different methods.

You place HTML Form Controls (input) in the component template and bind them to the data model attributes using commands such as ngModel.

You do not need to create an angular form control object, because angular will automatically create an angular form control object based on your data binding information. You are not pushing or pulling data values. Angular helped you deal with it in ngModel. Angular updates the changed data values.

For this reason, ngModel is no longer part of ReactiveFormsModule.

This means that you can write less code in the component class, but the template-driven form works asynchronously, which may complicate development in some cases.

Synchronous vs asynchronous

Responsive forms are synchronized. The template-driven form is asynchronous, which is the root of the difference.

In response forms, you can create a complete Form Control tree in the code. You can update or retrieve a value from the child form or parent form immediately, because all controls can access it.

The template-driven form delegates the creation of their form controls to instructions. To avoid "check and change" errors, these commands use more than one loop to create the entire control tree. This means that you have to wait a little while to operate the Space Form in any component class.

For example, if you inject a query by @ ViewChild (NgForm) to a form control and check it in the ngAfterViewInit lifecycle Hook, you will find that it has no child element. You must wait for a while and use setTimeout to wait. Then you can remove the value from the space and verify it or set it to a new value.

The asynchronous nature of template-driven forms also complicate unit tests. You must use async () or fakeAsync () to wrap your test block to avoid missing form values. If you are using a responsive form, everything will exist as you wish.

Which method is better?

Nothing is better. They are two different ways to build their own strengths and weaknesses. The most suitable method is correct. You can use either of the two methods in an application.

This article will only describe the examples and essence of the response. For template-driven forms, go to the form introduction page.

Next, you will write your own project to demonstrate the responsive form. Then you will learn about angular form classes and how to use them in responsive forms.

In summary, compared with the two-way Data Binding in ng1, ng2 retains this two-way binding capability (the underlying layer actually optimizes a lot), and the original ng-model command is upgraded to ngModel, the functions used remain unchanged.

At the same time, although the two-way Data Binding of ng2 has been greatly optimized, the asynchronous data binding method cannot be changed because ng2 cannot determine when data is bound, we cannot determine the arrival time of data for many network requests.

In ng1, this mechanism has some embarrassing scenarios. at least in some cases, I have to use setTimeout in some business scenarios to ensure that the data has been successfully bound to the watch loop of the scope, however, asynchronous data binding is inevitable unless we adapt ourselves to the actual project to rewrite angular code.

Therefore, ng2 provides the ability to adapt ngModel to specific project scenarios, that is, the Response Form introduced in the original article.

The relationship between ngModel and ngModel is that ngModel is the official implementation of responsive forms. When we bind data, it automatically implements several mechanisms used in response forms, if you need to strictly synchronize and bind data in real time, you do not need to use ngModel. You can write a responsive form in person. The steps cover the entire data model from the component template to the data model, however, ngModel can be used in a suitable scenario. The two form binding methods have their own advantages.

1. Use a responsive form

The ability of a responsive form is encapsulated in ReactiveFormsModule and included in the @ angular/forms package together with FormsModule.

Key Points of form classes:

1. AbstractControl is the abstract base class of the FormControl, FormGroup, and FormArray instance form classes. It provides their common behaviors and attributes, including observable.

2. FormControl checks the value in a single form control and verifies the status. It notifies HTML Form Controls (such as input ).

3. FormGroup is responsible for the value and verification status of a group of AbstractControl instances. Group attributes include their child controls. The top-level form of your component is a FormGroup.

4. FormArray is responsible for verifying the value and status of the value index array of the AbstractControl instance.

2. FormControl

The most core command is FormControl, which is the underlying ngModel. It is bound to the defined data model field in the template tag, just like this:

In the component code, you must declare the name field in the previous example as the FormControl class:

export class HeroDetailComponent1 { name = new FormControl();}

3. FormGroup

Groups multiple FormControl objects into FormGroup for convenient management. The definition method is as follows:

import { Component }       from '@angular/core';import { FormControl, FormGroup } from '@angular/forms';export class HeroDetailComponent2 { heroForm = new FormGroup ({  name: new FormControl() });}

In this case, the template tag should also be grouped to write:

The current effect is to read its value and some additional status changes from heroForm in real time.

You can add two tags to the template to display data changes:

<p>Form value: {{ heroForm.value | json }}</p><p>Form status: {{ heroForm.status | json }}</p>

4. FormBuilder

Another new concept is FormBuilder, which is used to help create form classes:

1. display the type of the declared heroForm attribute as FormGroup, which will be initialized later

2. Inject FormBuilder into the constructor

3. Use FormsBuilder to add a new method to define heroForm, which is called createForm.

4. Execute the createForm method in the constructor.

export class HeroDetailComponent3 { heroForm: FormGroup; // <--- heroForm is of type FormGroup constructor(private fb: FormBuilder) { // <--- inject FormBuilder  this.createForm(); } createForm() {  this.heroForm = this.fb.group({   name: '', // <--- the FormControl called "name"  }); }}

In the above example, you can dynamically and quickly create a form class by executing the createForm method. It can be used in some scenarios where the form class needs to be changed.

5. setValue and patchValue

These two methods are actually used to assign values to the form model. Because the data displayed in the form cannot be the same as the actual underlying data, otherwise the source data will be contaminated once the input data is changed, the two methods are used to assign the source data to the form model data.

You can call a value whenever a value is required. The setValue must be accurately assigned and an error is reported when the data does not match. The patchValue is not so strict, but an object can be passed, no error is reported if the request does not match.

What we need to do is to manually execute setValue in the ngOnChanges callback of the ng2 component to set the data value. For example:

ngOnChanges()  this.heroForm.setValue({   name:  this.hero.name,   address: this.hero.addresses[0] || new Address()  }); }

At the same time, ng2 also provides a reset method to re-call the setValue method (setValue itself seems to be only used for one-time value assignment ).

6. FormArray

FormArray is used to deal with the FormGroups list. For example, a hero may have multiple address fields, and the address field itself is a FormGroup. In this case, FormArray is used:

this.heroForm = this.fb.group({ name: ['', Validators.required ], secretLairs: this.fb.array([]), // <-- secretLairs as an empty FormArray power: '', sidekick: ''});

To obtain FormArray, you must use a get method provided by FormGroup:

get secretLairs(): FormArray { return this.heroForm.get('secretLairs') as FormArray;};

The displayed template is as follows:

<div formArrayName="secretLairs" class="well well-lg"> <div *ngFor="let address of secretLairs.controls; let i=index" [formGroupName]="i" >  <!-- The repeated address template --> </div></div>

The effect is to define this FormArray and then use ngFor to traverse the form List (directly using ngModel and ngFor can save a lot of trouble ...).

Summary:

At present, the use of ng2 does not involve complex forms, so I do not have a deep understanding of the content mentioned in the original article. In addition, the content written by foreigners is usually too complete, I like to use a long article to illustrate a simple knowledge point. Therefore, in the second half of this article, there are not many shadows of the original articles. This is just a poor generalization by the author and I have not done much practice.

Looking back at the Response Form capabilities of ng2, the commands and services provided are just like this (FormControl, FormGroup, FormArray, FormBuilder, and several functional methods ), cleverly using these capabilities to complete a powerful form interface, the coding experience is definitely far beyond the traditional jQuery method of forcibly reading node values from the DOM, in addition to simple ngModel capabilities, the ngModel provides more specific and powerful data binding solutions, as well as form verification not mentioned in this article, it is also handy to implement this responsive form solution provided by ng2.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.