@ngx-boilerplate-functions/forms is a utility package designed to simplify form handling in Angular applications. It provides helper functions for managing FormGroup
and FormControl
operations efficiently.
To install the package, use npm or yarn:
npm install @ngx-boilerplate-functions/forms
or
yarn add @ngx-boilerplate-functions/forms
import { FormBuilder, FormGroup, FormControl, ValidatorFn } from '@angular/forms';
import { FormsFunctionsService } from 'ngx-form-boilerplate';
Inject the service into your component:
constructor(private formService: FormsFunctionsService) {}
-
name
: The field name (required). -
validations?
: An array of Angular validation functions. -
defaultValue?
: The default value of the field. -
value?
: The current value of the field. -
options?
: Additional options likeonlySelf
andemitEvent
. -
formatType?
: Defines how the value should be formatted (string
,number
,date
, etc.). -
dateFormat?
: Specifies a date format whenformatType
is set todate
. -
mappedKey?
: Defines a different key for mapping data.
Initializes a FormGroup
or UntypedFormGroup
based on the provided fields.
-
formBuilder: FormBuilder | UntypedFormBuilder
- The form builder instance. -
fields: InitializeFormGroupInput[]
- An array of field definitions.
export type InitializeFormGroupInput = {
name: string;
value?: any;
validations?: ValidatorFn[];
}
FormGroup | UntypedFormGroup | undefined
- The initialized form group.
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService, InitializeFormGroupInput} from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder
) {}
initializeFormGroup() {
const fields: InitializeFormGroupInput[] = [
{ name: 'username', value: '', validations: [Validators.required] },
]
this.form = this.formService.initializeFormGroup(this.fb, fields);
}
}
Resets the form to its initial state or with provided default field values.
formGroup: FormGroup | UntypedFormGroup
defaultFields?: CommonFieldInput[]
export type CommonFieldInput = {
name: string;
value?: any;
}
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService, CommonFieldInput} from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder
) {
this.form = this.fb.group({
name: ['Donald Olmo', [Validators.required]],
address: ['Portland', [Validators.required]]
})
}
resetFormGroup() {
const defaultFields: CommonFieldInput[] = [
{ name: 'name'},
{ name: 'address', value: '-'}
]
this.formService.resetFormGroup(this.form, defaultFields);
console.log(this.form.value)
}
}
Validates if two form controls match (e.g., password confirmation).
formGroup: FormGroup | UntypedFormGroup
controlName: string
matchingControlName: string
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService } from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder
) {
this.form = this.fb.group({
email: [null, [Validators.required]],
password: ['123456', [Validators.required]],
confirmPassword: ['654321', [Validators.required]]
})
}
checkIfFormControlsMatch() {
this.formService.checkIfFormControlsMatch(this.form, 'password', 'confirmPassword');
console.log(this.form.controls['confirmPassword'].errors)
}
}
{ mustMatch: true }
Retrieves error messages for a specific form control.
control: FormControl | UntypedFormControl
errorType: 'required' | 'minLength' | 'maxLength' | 'pattern' | 'min' | 'max' | 'email'
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService } from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder
) {
this.form = this.fb.group({
email: [null, [Validators.required]],
password: [null, [Validators.required]],
})
}
getFormControlErrorMessage() {
const errorMessage = this.formService.getFormControlErrorMessage(this.form.get('email'), 'required');
console.log(errorMessage)
}
}
Checks if the entire form group is valid.
formGroup: FormGroup | UntypedFormGroup
boolean
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService } from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder
) {
this.form = this.fb.group({
email: [null, [Validators.required]],
password: [null, [Validators.required]],
})
}
isFormControlValidWithControlMark(): boolean {
const isValid = this.formService.isFormGroupValid(this.form);
console.log(isValid)
}
}
Marks all form controls as touched.
form: FormGroup | UntypedFormGroup
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService } from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder
) {
this.form = this.fb.group({
email: [null, [Validators.required]],
password: [null, [Validators.required]],
})
}
markAllControlsAsTouched() {
this.formService.markAllControlsAsTouched(this.form);
console.log(this.form.get('email')?.touched)
}
}
true
Dynamically adds a form control to an existing form group.
form: FormGroup | UntypedFormGroup
controlName: string
control: FormControl | UntypedFormControl
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService } from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder
) {
this.form = this.fb.group({
email: [null, [Validators.required]],
password: [null, [Validators.required]],
})
}
addFormControl() {
this.formService.addFormControl(this.form, 'address', new FormControl('Dar es Salaam'));
console.log(this.form.contains('address'));
console.log(this.form.get('address').value);
}
}
true
Dar es Salaam
Removes a form control from the form group.
form: FormGroup
controlName: string
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService } from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder
) {
this.form = this.fb.group({
email: [null, [Validators.required]],
password: [null, [Validators.required]],
})
}
removeFormControl() {
this.formService.removeFormControl(this.form, 'password');
console.log(this.form.contains('password'));
}
}
false
Patches values to a form group, optionally mapping field names using passed payload.
formGroup: FormGroup | UntypedFormGroup
data: any
mappedKeys?: MappedKeysInput[]
export type MappedKeysInput = {
name: string;
mappedKey?: string;
}
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService, MappedKeysInput} from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder) {
this.form = this.fb.group({
email: [null],
name: [null],
address: [null]
})
}
patchFormGroupValues() {
const data = {
myEmail: 'user@example.com',
name: 'New User',
address: 'Dar es Salaam'
}
const mappedKeys: MappedKeysInput[] = [{name: 'email', mappedKey: 'myEmail'];
this.formService.patchFormGroupValues(this.form, data, mappedKeys);
console.log(this.form.value);
}
}
{
"email": "user@example.com",
"name": "New User",
"address": "Dar es Salaam"
}
Dynamically sets validation rules for form controls.
formGroup: FormGroup | UntypedFormGroup
fields: FormGroupValidationInput[]
export type FormGroupValidationInput = {
name: string;
validations?: ValidatorFn[];
}
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService, FormGroupValidationInput} from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder) {
this.form = this.fb.group({
email: [null],
password: [null]
})
}
setFormGroupValidations() {
const fields: FormGroupValidationInput[] = [
{name: 'email', validations: [Validators.required, Validators.email]},
{name: 'password', validations: [Validators.required, Validators.minLength(6)]}
]
this.formService.setFormGroupValidations(this.form, fields);
}
}
Removes validations from specified form controls and resets their values to default or null.
formGroup: FormGroup | UntypedFormGroup
fields: RemoveFormGroupValidationInput[]
export type RemoveFormGroupValidationInput = {
name: string;
defaultValue?: any;
}
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService, RemoveFormGroupValidationInput} from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder
) {
this.form = this.fb.group({
email: [null, [Validators.required]],
password: [null, [Validators.required]]
})
}
removeFormGroupValidations() {
const fields: RemoveFormGroupValidationInput[] = [
{name: 'email', defaultValue: 'user@example.com'},
{name: 'password'}
]
this.formService.removeFormGroupValidations(this.form, fields);
}
}
Field email will have a default value of user@example.com
Adds or removes specific fields in the form payload before submission.
formGroup: FormGroup | UntypedFormGroup
fieldsToAdd: CommonFieldInput[]
fieldsToRemove: string[]
export type CommonFieldInput = {
name: string;
value?: any;
}
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService, CommonFieldInput} from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder
) {
this.form = this.fb.group({
name: ['Donald Olmo', [Validators.required]],
address: ['Portland', [Validators.required]]
})
}
addAndRemoveFieldsOnSubmission() {
const fieldsToAdd: CommonFieldInput[] = [{name: 'email', value: 'user@example.com'}]
const fieldsToRemove = ['address']
const updatedPayload = this.formService.addAndRemoveFieldsOnSubmission(this.form, fieldsToAdd, fieldsToRemove);
console.log(updatedPayload);
}
}
{
"name": "Donald Olmo", "email": "user@example.com"
}
Disable specified field in a FormGroup or UntypedFormGroup.
formGroup: FormGroup | UntypedFormGroup
fieldsToDisable: DisableFieldInput[]
export type DisableFieldInput = {
name: string;
options?: { onlySelf?: boolean; emitEvent?: boolean;};
}
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService, DisableFieldInput} from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder
) {
this.form = this.fb.group({
name: ['Donald Olmo', [Validators.required]],
address: ['Portland', [Validators.required]]
})
}
disableFields() {
const fieldsToDisable: DisableFieldInput[] = [
{ name: 'name'},
{ name: 'address', options: { onlySelf: true, emitEvent: true }}
]
this.formService.disableFields(this.form, fieldsToDisable);
}
}
{
"name": "Donald Olmo", "email": "user@example.com"
}
Set values to fields in the FormGroup / UntypedFormGroup.
formGroup: FormGroup | UntypedFormGroup
fieldsToSet: CommonFieldInput[]
export type CommonFieldInput = {
name: string;
value?: any;
}
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService, CommonFieldInput} from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder
) {
this.form = this.fb.group({
name: [null, [Validators.required]],
address: [null, [Validators.required]]
})
}
patchValuesToFields() {
const fieldsToSet: CommonFieldInput[] = [{name: 'name', value: 'John Doe'},
{name: 'address', value: 'Dar es Salaam'}]
this.formService.patchValuesToFields(this.form, fieldsToSet);
console.log(this.form.value);
}
}
{
"name": "John Doe", "address": "Dar es Salaam"
}
Add or/and remove fields in the FormGroup / UntypedFormGroup.
formGroup: FormGroup | UntypedFormGroup
fieldsToAdd: InitializeFormGroupInput[]
fieldsToRemove: {name: string, emitEvent?: boolean}[]
export type InitializeFormGroupInput = {
name: string;
value?: any;
validations?: ValidatorFn[];
}
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService, InitializeFormGroupInput} from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder
) {
this.form = this.fb.group({
name: [null, [Validators.required]],
address: [null, [Validators.required]]
})
}
changeFormControlFields() {
const fieldsToAdd: InitializeFormGroupInput[] = [{name: 'email', value: 'user@example.com', validations: [Validators.required]},
{name: 'address', value: 'Dar es Salaam'}]
const fieldsToRemove: {name: string, emitEvent?: boolean}[] = [{ name: 'address', emitEvent: true }]
this.formService.changeFormControlFields(this.form, fieldsToAdd, fieldsToRemove);
console.log(this.form.value);
}
}
Check form control is valid using control marks.
control: FormControl | UntypedFormControl
controlMarks: ('dirty' | 'pristine' | 'touched' | 'invalid')[]
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService } from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder
) {
this.form = this.fb.group({
email: [null, [Validators.required]],
password: [null, [Validators.required]],
})
}
isFormControlValidWithControlMark(): boolean {
const isValid = this.formService.isFormControlValidWithControlMark(this.form.get('email'), ['dirty', 'pristine']);
console.log(isValid)
}
}
Get error messages from FormGroup or UntypedFormGroup.
formGroup: FormGroup | UntypedFormGroup
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService } from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder
) {
this.form = this.fb.group({
email: [null, [Validators.required, Validators.email]],
password: [null, [Validators.required]],
})
}
getFormGroupErrorMessages(): boolean {
const errors = this.formService.getFormGroupErrorMessages(this.form);
console.log(errors)
}
}
{
"email": ["Email is required", "Email should be valid email"],
"password": ["Password is required"]
}
Formats to specified type or format, assigns value and removes specific fields in the form payload before submission.
formGroup: FormGroup | UntypedFormGroup
fieldsToFormat: FormatFieldInput[]
export type FormatFieldInput = {
name: string;
formatType?: 'string' | 'number' | 'float' | 'boolean' | 'date' | 'remove' | 'add';
dateFormat?: string;
value?: any;
}
import {UntypedFormBuilder, UntypedFormGroup, ValidatorFn, Validators} from "@angular/forms";
import {FormsFunctionsService, FormatFieldInput} from "@ngx-boilerplate-functions/forms";
export class TestingComponent {
form: UntypedFormGroup;
constructor(private formService: FormsFunctionsService,
private fb: UntypedFormBuilder
) {
this.form = this.fb.group({
name: ['Donald Olmo', [Validators.required]],
address: ['Portland', [Validators.required]],
year: [1990, [Validators.required]]
})
}
formatPayloadForSubmission() {
const fieldsToFormat: FormatFieldInput[] = [{name: 'year', formatType: 'string'}]
const updatedPayload = this.formService.formatPayloadForSubmission(this.form, fieldsToFormat);
console.log(updatedPayload);
}
}
{
"name": "Donald Olmo",
"email": "user@example.com",
"year": "1990"
}
Feel free to submit issues or pull requests on GitHub to improve the package.
This package is released under the MIT License.