Angular implements responsive forms and angular response forms

Source: Internet
Author: User
Tags export class

Angular implements responsive forms and angular response forms

Introduction

Angular provides a total of three form implementation methods: Template-driven Forms (Template-driven Forms), Reactive Forms (responsive Forms), and Dynamic Forms (Dynamic Forms ). This article only describes responsive forms.

What is a responsive form? In fact, the idea is similar to that we previously implemented using JQuery or other frameworks. We use HTML to display data, and then define a certain validator, validation rules, and verification tips, after verification is triggered by an event, the prompt message indicating that the verification fails is displayed. Angular is used, and the syntax provided by Angular is used to implement this verification process.

Use

Next we will introduce how to use responsive forms through code examples.

Introduce responsive form Module

Introduce the responsive form module in the module where we want to use the responsive form. For example, if we use a responsive form in the article module, we need to add the ReactiveFormsModule in imports. The Code is as follows:

@NgModule({ imports: [ RouterModule, RouterModule.forChild(articleRoutes), SharedModule, ReactiveFormsModule, NgbModule.forRoot() ], declarations: [ HomeComponent, DetailComponent, CommentComponent, CommentViewComponent ], providers: [ HomeService, DetailService, CommentService ]})export class ArticleModule { }

Compile the validator code

First, the form contains three fields: nickname, email, and content. The nickname is used to add a required checker, the email is used to add a required and email format checker, And the content is used to add a required checker.

First, inject the FormBuilder object into CommentComponent, add the commentForm form group, and create a comment object comment.

public commentForm: FormGroup;public comment: Comment = new Comment();constructor(private formBuilder: FormBuilder){}

Define the validator prompt language validationMessages. formErrors is the prompt language displayed in the template. The prompt language comes from validationMessages.

Public formErrors = {"nickname": "", "email": "", "content": "", "formError": ""} public validationMessages = {"nickname ": {"required": "nickname cannot be blank",}, "email": {"required": "Mailbox cannot be blank", "pattern ": "Enter the correct email address"}, "content": {"required": "content cannot be blank "}}

Construct a form in the function started by the component. At this time, A validator is added for each field and the verification is triggered when it is bound. Here we will trigger the verification when each value changes.

ngOnInit(): void { this.buildForm();}private buildForm() { this.commentForm = this.formBuilder.group({ "nickname":[  this.comment.nickname,  [  Validators.required  ] ], "email": [  this.comment.email,  [  Validators.required,  Validators.pattern("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$")  ] ], "content": [  this.comment.content,  [  Validators.required  ] ] }); this.commentForm.valueChanges.subscribe(data => this.onValueChanged(data)); this.onValueChanged();}

The onValueChanged () method realizes that the validation of the field fails, and then assigns the validationMessages prompt of the field to formErrors. In the template, it determines if formErrors. if fields such as email are not blank, the modified content is displayed, that is, the prompt of the validator.

onValueChanged(data?: any) { if (!this.commentForm) { return; } const form = this.commentForm; for (const field in this.formErrors) { this.formErrors[field] = ''; const control = form.get(field); if (control && control.dirty && !control.valid) {  const messages = this.validationMessages[field];  for (const key in control.errors) {  this.formErrors[field] += messages[key] + ' ';  } } }}

HTML template code

[FormGroup] = "commentForm", novalidate, formControlName = "nickname", and * ngIf = "formErrors. the nickname points do not refer to specific points, but focus on every part of these syntaxes. You need to modify them according to your code when implementing them yourself.

Another example is (ngSubmit) = "sendComment ()", which defines the function called when the form is clicked and submitted.

<form [formGroup]="commentForm" (ngSubmit)="sendComment()" role="form" novalidate> <div class="control-group"> <div class="form-group floating-label-form-group controls" [ngClass]="{'has-error': formErrors.nickname}">  <label>{{ 'comment.nickname' | translate }}</label>  <input formControlName="nickname" type="text" class="form-control" placeholder="{{ 'comment.nickname' | translate }}">  <p *ngIf="formErrors.nickname" class="help-block text-danger">  {{ formErrors.nickname }}  </p> </div> </div> <div class="control-group" > <div class="form-group floating-label-form-group controls" [ngClass]="{'has-error': formErrors.email}">  <label>{{ 'comment.email' | translate }}</label>  <input formControlName="email" type="email" class="form-control" placeholder="{{ 'comment.email' | translate }}">  <p *ngIf="formErrors.email" class="help-block text-danger">  {{ formErrors.email }}  </p> </div> </div> <div class="control-group"> <div class="form-group floating-label-form-group controls" [ngClass]="{'has-error': formErrors.content}">  <label>{{ 'comment.content' | translate }}</label>  <textarea formControlName="content" rows="5" class="form-control" placeholder="{{ 'comment.content' | translate }}"></textarea>  <p *ngIf="formErrors.content" class="help-block text-danger">  {{ formErrors.content }}  </p> </div> </div> <p *ngIf="formErrors.formError" class="help-block text-danger"> {{ formErrors.formError }} </p> <br> <div id="success"></div> <div class="form-group"> <button [disabled]="commentForm.invalid" type="submit" class="btn btn-secondary" >{{ 'comment.submit' | translate }}</button> </div></form>

GitHub code

References

Reactive Forms


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

Related Article

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.