Friday 8 June 2018

Dynamic Reactive Forms using FormArray.

To work with a FormArray do the following:
  1. Define the items in the array; that is, FormControls or FormGroups.
  2. Initialize the array with items created from data in the data model.
  3. Add and remove items as the user requires.
In module
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

In Component
import {
FormArray,
FormBuilder,
FormGroup,
FormControl,
Validators }
from '@angular/forms';


export class AddUserComponent implements OnInit {
registrationForm: FormGroup;
formErrors = {};
validationMessages = {};
constructor(private _fb: FormBuilder ) { }

ngOnInit() {
this.setFormErrors();
this.creatForms();
this.getDepartmentDDL();
}
getDepartmentDDL() {
// get list of deparment
this.setFormArray(departmentData)
}

setFormErrors() {
this.formErrors = {
'first_Name': '',
'phone_number': '',
'email': '',
'department': '',
'password': '',
'confirm_password': ''
};
this.validationMessages = {
'first_Name': {
'required': 'First name is required.',
'minlength': 'First name must be at least 4 characters long.',
'maxlength': 'First name cannot be more than 20 characters long.'
},
'phone_number': {
'required': 'Phone number is required.',
'pattern': 'Phone number is invalid.',
'maxlength': 'Phone number cannot be more than 20 number long.'
},
'email': {
'required': 'E-mail is required.',
'email': 'E-mail is invalid.',
'maxlength': 'E-mail cannot be more than 100 characters long.'
},
'password': {
'required': 'Password is required.',
'minlength': 'Password must be at least 4 characters long.',
'maxlength': 'Password cannot be more than 35 characters long.'
},
'confirm_password': {
'required': 'Confirm password is required.',
'invalid': 'Password do not match!'
}
};
}
creatForms() {
this.registrationForm = this._fb.group({
first_Name: [this.user.firstname, [Validators.required,
Validators.minLength(4), Validators.maxLength(20)]],
phone_number: ['', [Validators.required,
Validators.pattern('[0-9\+\-\]+'), Validators.maxLength(20)]],
email: [{ value: this.user.email, disabled: this.isEdit },
[Validators.required, Validators.email, Validators.maxLength(100)]],
password: [this.user.password, this.passwordValidator],
confirm_password: [this.user.password, this.cnfPasswordValidator],
department: this._fb.array([]),
});
this.registrationForm.valueChanges.subscribe(data => this.onFormChanged(data));
}
setFormArray(departmentData) {
const arrayItem = departmentData.map(item => {
const obj = Object.assign({}, item);
obj.selectedArr = '';
return this._fb.group(obj)
});
const roleItems = this._fb.array(arrayItem);
this.registrationForm.setControl(department, roleItems);
}
passwordconfirmation(c: AbstractControl): any {
if (!c.parent || !c) { return; }
const pwd = c.parent.get('password');
const cpwd = c.parent.get('confirm_password')

if (!pwd.value || !cpwd.value) { return; }
if (pwd.value !== cpwd.value) {
return { invalid: true };
}
}
clearConfirmPass() {
this.registrationForm.controls['confirm_password'].setValue(null)
}
onFormChanged(data?: any) {
if (!this.registrationForm) { return; }
const form = this.registrationForm;
// tslint:disable-next-line:forin
for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
// tslint:disable-next-line:forin
for (const key in control.errors) {
this.formErrors[field] += messages[key] + ' ';
}
}
}
}

onClickSave() {
const newUser = {};
newUser['firstname'] = this.registrationForm.value['first_Name'];
newUser['Phone'] = this.registrationForm.value['phone_number'];
newUser['email'] = this.registrationForm.value['email'];
newUser['department'] = this.getDepartmentArr();
}
getDepartmentArr() {
const selectedDepartmentArr = [];
this.registrationForm.value.department.map(item => {
if (item.selectedArr) {
selectedDepartmentArr.push({ sfdcId: item.id, Name: item.Name,
status: item.selectedArr })
}
})
return selectedDepartmentArr;
}
}



In HTML


<form #userForm="ngForm" [formGroup]="registrationForm"
(ngSubmit)="onClickSave()" class="form-material" name='userForm'>
<div class="row m-t-10">
<div class="col-6">
<span>First Name
<span class="text-danger">*</span>
</span>
<input type="text" formControlName="first_Name" name="first_Name"
class="form-control">
<small *ngIf="formErrors.first_Name"
class="help-block text-danger">{{ formErrors.first_Name }}</small>
</div>
</div>
<div class="row m-t-10">
<div class="col-6">
<span>Phone
<span class="text-danger">*</span>
</span>
<input formControlName="phone_number" type="text" class="form-control">
<small *ngIf="formErrors.phone_number"
class="help-block text-danger">{{ formErrors.phone_number }}</small>
</div>
<div class="col-6">
<span>Email
<span class="text-danger">*</span>
</span>
<input formControlName="email" type="text" class="form-control">
<small *ngIf="formErrors.email"
class="help-block text-danger">{{ formErrors.email }}</small>
</div>
</div>

<div formArrayName="department" class="border-t vertical-scroll-user">
<table>
<tr class="m-t-5" *ngFor="let role of department; let i=index"
[formGroupName]="i">
<td>
<span>{{i+1}}.</span>
<span>{{role.Name}}</span>
<span class="text-danger">*</span>
</td>
<td>
<input type="radio" id="{{'active-' + i}}" value="1"
formControlName="selectedArr" class="radio-col-light-blue">
<label for="{{'active-' + i}}">Active</label>
</td>
</tr>
</table>
</div>
</form>









No comments:

Post a Comment