Overview
The FormStructure class is the core class for creating and managing dynamic forms in Mat Dynamic Form. It extends ObjectBase and provides comprehensive methods for form control management, validation, and value handling.
Source: projects/mat-dynamic-form/src/lib/models/FormStructure.ts:12
Constructor
constructor(title?: string, nodes?: Node[], validateActions?: Button[])
Creates a new FormStructure instance.
The title displayed at the top of the form
Array of form nodes (inputs, dropdowns, etc.) to render. See Node
Array of action buttons (max 4 allowed). See Button
The constructor throws an error if more than 4 validate actions are provided.
Properties
Public Properties
Array of form nodes that define the form fields
Array of action buttons displayed at the bottom of the form
Number of columns for form layout (min: 1, max: 4)
Maximum height of the form container
If true, only the form content scrolls (not the entire container)
appearance
MatFormFieldAppearance
default:"'standard'"
Material form field appearance: 'standard' | 'fill' | 'outline'
Whether to display the form title
globalValidators
ValidatorFn | ValidatorFn[] | null
Global validators applied to all form controls
Whether to validate disabled controls
Methods
setFromGroup
setFromGroup(formGroup: FormGroup): void
Sets the internal FormGroup instance.
The Angular FormGroup instance to manage
getFormGroup(): FormGroup
Returns the internal FormGroup instance.
The managed Angular FormGroup
Control and Node Access
getControlById
getControlById(controlId: string): AbstractControl | null
Retrieves a form control by its ID.
Source: FormStructure.ts:80
The unique identifier of the control
The control instance, or null if not found
getNodeById
getNodeById<T extends Node>(nodeId: string): T
Retrieves a node by its ID and updates its value from the form control.
Source: FormStructure.ts:91
The unique identifier of the node
The node instance with updated value
getActionById
getActionById<T extends Node>(nodeId: string): Button
Retrieves a validate action button by its ID.
Source: FormStructure.ts:108
The unique identifier of the action button
Value Management
getValue
Returns the current form values (excluding disabled controls).
Source: FormStructure.ts:139
Object containing form values by control ID
getRawValue
Returns all form values including disabled controls.
Source: FormStructure.ts:149
Object containing all form values by control ID
patchValue
patchValue<T>(newValue: DataSet<T>): boolean
Updates form control values from a DataSet object.
Source: FormStructure.ts:179
Object mapping control IDs to new values. See DataSet
True if successful, false if formGroup is not initialized
Throws ReferenceException if a control ID in newValue doesn’t exist in the form.
reset
Resets all form controls to their initial values.
Source: FormStructure.ts:115
True if successful, false otherwise
remapValues
Re-applies default values from node definitions to form controls.
Source: FormStructure.ts:127
Validation
isValid
Checks if the entire form is valid.
Source: FormStructure.ts:197
True if all validations pass
isInvalid
Checks if the form has any validation errors.
Source: FormStructure.ts:222
True if any validation fails
addValidators
addValidators(id: string, validators: Validator): void
Adds synchronous validators to a specific control without replacing existing ones.
Source: FormStructure.ts:332
The control ID to add validators to
ValidatorFn, ValidatorFn[], or null
addAsyncValidators
addAsyncValidators(id: string, validators: AsyncValidator): void
Adds asynchronous validators to a specific control.
Source: FormStructure.ts:344
The control ID to add validators to
AsyncValidatorFn, AsyncValidatorFn[], or null
setValidator
setValidator(id: string, validators: Validator): void
Replaces all synchronous validators on a control.
Source: FormStructure.ts:356
The control ID to set validators for
ValidatorFn, ValidatorFn[], or null
setAsyncValidator
setAsyncValidator(id: string, validators: AsyncValidator): void
Replaces all asynchronous validators on a control.
Source: FormStructure.ts:370
The control ID to set validators for
AsyncValidatorFn, AsyncValidatorFn[], or null
Dynamic Node Management
createNodes
createNodes(from: number, nodes: Node[]): void
Inserts multiple nodes into the form at a specific position.
Source: FormStructure.ts:232
The index position to insert nodes at
removeNodes
removeNodes(nodes: Node[]): void
Removes multiple nodes from the form.
Source: FormStructure.ts:243
createFormControl(node: Node): void
Creates or updates a form control for a given node.
Source: FormStructure.ts:293
The node to create a control for
removeFormControl(node: Node): void
Removes a form control from the FormGroup.
Source: FormStructure.ts:284
The node whose control should be removed
createValidateActions
createValidateActions(from: number, nodes: Button[]): void
Inserts multiple action buttons at a specific position.
Source: FormStructure.ts:255
The index position to insert buttons at
Array of button nodes to insert
removeValidateActions
removeValidateActions(nodes: Button[]): void
Removes multiple action buttons from the form.
Source: FormStructure.ts:266
Array of button nodes to remove
Utility Methods
fromGroupSize
Counts the total number of controls in the FormGroup.
Source: FormStructure.ts:275
Total count of form controls (recursively counts nested groups/arrays)
addNodeEvent
addNodeEvent(node: Node): void
Attaches event listeners to a node based on its action configuration.
Source: FormStructure.ts:383
The node to attach events to
Usage Examples
import { FormStructure, Input, Button, Dropdown, OptionChild } from 'mat-dynamic-form';
import { Validators } from '@angular/forms';
const structure = new FormStructure(
'User Registration',
[
new Input('username', 'Username', '', null, false, 'person', 'Username is required', false, false, Validators.required),
new Input('email', 'Email', '', null, false, 'email', 'Email is required', false, false, [Validators.required, Validators.email]),
new Dropdown(
'country',
'Country',
[
new OptionChild('United States', 'us'),
new OptionChild('Canada', 'ca'),
new OptionChild('Mexico', 'mx')
],
'us'
)
],
[
new Button('submit', 'Submit', {
type: 'click',
style: 'primary',
onEvent: ({ structure }) => {
if (structure.isValid()) {
const values = structure.getValue();
console.log('Form submitted:', values);
}
}
}, false, 'send', false, true)
]
);
// Configure appearance
structure.appearance = 'outline';
structure.nodeGrid = 2;
structure.maxParentHeight = '80vh';
Accessing and Updating Values
// Get specific node
const usernameNode = structure.getNodeById<Input>('username');
console.log('Username:', usernameNode.value);
// Get specific control
const emailControl = structure.getControlById('email');
emailControl.setValue('[email protected]');
// Patch multiple values
structure.patchValue({
username: 'johndoe',
email: '[email protected]',
country: 'ca'
});
// Get all values
const formData = structure.getValue<{
username: string;
email: string;
country: string;
}>();
// Reset form
structure.reset();
import { Input, Checkbox } from 'mat-dynamic-form';
// Add new fields dynamically
const newFields = [
new Input('phone', 'Phone Number', '', null, false, 'phone'),
new Checkbox('newsletter', 'Subscribe to newsletter', false)
];
structure.createNodes(2, newFields); // Insert at position 2
// Remove fields
structure.removeNodes(newFields);
Validation Management
import { Validators } from '@angular/forms';
// Add validators to existing control
structure.addValidators('username', Validators.minLength(3));
// Replace validators
structure.setValidator('email', [
Validators.required,
Validators.email,
Validators.pattern(/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/)
]);
// Add async validator
structure.addAsyncValidators('username', (control) => {
return checkUsernameAvailability(control.value).pipe(
map(available => available ? null : { usernameTaken: true })
);
});
// Check validation status
if (structure.isValid()) {
console.log('Form is valid');
} else {
console.log('Form has errors');
}
Global Validators
import { AbstractControl, ValidationErrors } from '@angular/forms';
// Custom global validator
function noSpecialCharsValidator(control: AbstractControl): ValidationErrors | null {
const hasSpecialChars = /[!@#$%^&*(),.?":{}|<>]/.test(control.value);
return hasSpecialChars ? { specialChars: true } : null;
}
structure.globalValidators = noSpecialCharsValidator;
Working with Actions
import { Button, ActionEvent } from 'mat-dynamic-form';
const submitButton = new Button(
'submit',
'Submit Form',
{
type: 'click',
style: 'primary',
onEvent: ({ event, structure }: ActionEvent) => {
if (structure.isValid()) {
const data = structure.getRawValue();
submitToAPI(data);
} else {
console.error('Form is invalid');
}
}
},
false,
'send',
false,
true, // validateForm
({ structure }) => {
// Custom validation logic
return structure.isValid() && structure.getValue().terms === true;
}
);
const resetButton = new Button(
'reset',
'Reset',
{
type: 'click',
style: 'warn',
onEvent: ({ structure }) => {
structure.reset();
}
}
);
structure.validateActions = [submitButton, resetButton];
Deprecated Methods
The following methods are deprecated and will be removed in future versions:
pathValue (Deprecated)
pathValue<T>(newValue: DataSet<T>): boolean
Deprecated since: v1.4.0
Removed in: v1.5.0
Use instead: patchValue
isInalid (Deprecated)
Deprecated since: v1.4.0
Removed in: v1.5.0
Use instead: isInvalid