未加星标

Dynamic FormGroup Custom Validation in Angular2

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二03 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

Dynamic FormGroup Custom Validation in Angular2

In this post I will show you how to create nested FormGroups to create a custom validator. This works well for related form inputs, such as checkboxes. If you are new to Angular 2 forms, check out Thoughtram’s post on reactive forms it’s a good read.

Getting Started

To review,Angular 2 has both model-driven forms as well as template-driven forms. I am using the model-driven reactive form. As such, I have imported the necessary classes from the @angular/forms module.

import { FormBuilder, FormControl, FormGroup, ReactiveFormsModule, Validators } from "@angular/forms"

I have imported the FormBuilder , FormControl , FormGroup and Validators classes. A quick overview of these:

FormBuilder this enables us to use some short-hand syntax for creating our FormGroup s. FormControl this represents a single control (or HTMLFormElement ). FormGroup this represents a group of form fields. We will also use the FormGroupDirective in our view. Validators this class provides some built-in validators that are used by our form controls. Form Template Before we get to the form template, I want to create an array of days of the week and store this as a public variable in my component. This is only because I am going to use the name and values when creating the checkboxes in my form. You could simply create the necessary input[type=”checkbox”] elements in your template instead. interface IDay {
name: string;
value: string;
}
@Component({})
export class UpdateComponent implements ngOnInit {
public days: IDay[] = [
{value: "sunday", name:"Sunday"},
{value: "monday", name:"Monday"},
{value: "tuesday", name:"Tuesday"},
{value: "wednesday", name:"Wednesday"},
{value: "thursday", name:"Thursday"},
{value: "friday", name:"Friday"},
{value: "saturday", name:"Saturday"},
];
}

Now, let’s look at the form template:

<form [formGroup]="detailsForm" novalidate>
<input type="text" [formControl]="detailsForm.get('name')" [class.invalid]="!detailsForm.controls.name.valid">
<div formGroupName="days">
<p *ngFor="let day of days">
<input type="checkbox" [formControlName]="day.value" [class.invalid]="!detailsForm.controls.days.valid">
<label>{{day.name}}</label>
</div>
</div>
</form>

A couple of things to note:

The formuses the FormGroupDirective to specify the FormGroup variable in my controller. Next, I have create a simple text input field. I bind the formControl directive to the “name” FormControl instance in my detailsForm . I am also going to add the “invalid” class when the value is not valid. This field will be required. Next, I have created another FormGroup , this is within the detailsForm and is called days . This is defined using the FormGroupName directive. Within the days FormGroup I am looping over the array of IDay objects using the NgFor directive. Each checkbox input is wrapped in a paragraph. The checkbox input uses the FormControlName directive to bind to the value string value within the IDay object. I have also specified a class of “invalid” that will be applied to each checkbox input when the group is invalid. Last, I have a <label> element that displays the name string value within the IDay object. Building a FormGroup

Back to our controller, we now need to create our FormGroup variable named detailsForm . The detailsForm will contain all of the details about the FormControl s, any nested FormGroups, and their FormControl s.

@Component({})
export class UpdateComponent implements ngOnInit {
public detailsForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
public ngOnInit() {
//create daysFormGroup using FormGroup long-hand syntax
//this is so I can create a dynamic form from the array of IDay objects
let daysFormGroup: FormGroup = new FormGroup();
for (let day of this.days) {
let control: FormControl = new FormControl(day.value, Validators.required);
daysFormGroup.addControl(day.value, control);
}
//create detailsForm FormGroup using FormBuilder's short-hand syntax
this.detailsForm = this.formBuilder.group({
name: ["", Validators.required],
days: daysFormGroup
});
}
}

Let’s walk through this:

First, I define the detailsForm public variable that is of type FormGroup . In my constructor function I inject the FormBuilder . This FormBuilder will be available as a private variable in my class. I will use this later to use the FormBuilder.group() short-hand syntax for creating a FormGroup . In my ngOnInit method I create a daysFormGroup variable so that I can dynamically create the FormControl s based on the days defined. I could have easily hard-coded these controls, as well as the checkbox inputs in my template. In this example I also wanted to show the ability to use dynamic forms in Angular 2. Next, I create the detailsForm FormGroup using the FormBuilder . First, I have the name text input, which uses the required method in the Validators class to require a value. Then, I define the days FormGroup . Create Custom Validator for FormGroup

Now we can create our custom validator for the daysOfWeek FormGroup. I am going to create a new private method in my UpdateComponent named validateDays() . This method will be passed the FormGroup .

/**
* Validate the days checkboxes. At least one must be selected.
*
* @class UpdateComponent
* @method validateDays
* @return {null|Object} Null if valid.
*/
private validateDays(formGroup: FormGroup) {
for (let key in formGroup.controls) {
if (formGroup.controls.hasOwnProperty(key)) {
let control: FormControl = <FormControl>formGroup.controls[key];
if (control.value) {

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: ReactHTML
分页:12
转载请注明
本文标题:Dynamic FormGroup Custom Validation in Angular2
本站链接:http://www.codesec.net/view/483683.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(30)