Skip to main content

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.
title
string
The title displayed at the top of the form
nodes
Node[]
Array of form nodes (inputs, dropdowns, etc.) to render. See Node
validateActions
Button[]
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

title
string
The form title text
nodes
Node[]
Array of form nodes that define the form fields
validateActions
Button[]
Array of action buttons displayed at the bottom of the form
nodeGrid
number
default:"2"
Number of columns for form layout (min: 1, max: 4)
maxParentHeight
string
default:"100vh"
Maximum height of the form container
onlyScrollContent
boolean
default:"false"
If true, only the form content scrolls (not the entire container)
appearance
MatFormFieldAppearance
default:"'standard'"
Material form field appearance: 'standard' | 'fill' | 'outline'
showTitle
boolean
default:"true"
Whether to display the form title
globalValidators
ValidatorFn | ValidatorFn[] | null
Global validators applied to all form controls
validateEvenDisabled
boolean
default:"false"
Whether to validate disabled controls

Methods

Form Group Management

setFromGroup

setFromGroup(formGroup: FormGroup): void
Sets the internal FormGroup instance.
formGroup
FormGroup
required
The Angular FormGroup instance to manage

getFormGroup

getFormGroup(): FormGroup
Returns the internal FormGroup instance.
returns
FormGroup
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
controlId
string
required
The unique identifier of the control
returns
AbstractControl | null
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
nodeId
string
required
The unique identifier of the node
returns
T extends 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
nodeId
string
required
The unique identifier of the action button
returns
Button
The button instance

Value Management

getValue

getValue<T>(): T
Returns the current form values (excluding disabled controls). Source: FormStructure.ts:139
returns
T
Object containing form values by control ID

getRawValue

RawValue<T>(): T
Returns all form values including disabled controls. Source: FormStructure.ts:149
returns
T
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
newValue
DataSet<T>
required
Object mapping control IDs to new values. See DataSet
returns
boolean
True if successful, false if formGroup is not initialized
Throws ReferenceException if a control ID in newValue doesn’t exist in the form.

reset

reset(): boolean
Resets all form controls to their initial values. Source: FormStructure.ts:115
returns
boolean
True if successful, false otherwise

remapValues

remapValues(): void
Re-applies default values from node definitions to form controls. Source: FormStructure.ts:127

Validation

isValid

isValid(): boolean
Checks if the entire form is valid. Source: FormStructure.ts:197
returns
boolean
True if all validations pass

isInvalid

isInvalid(): boolean
Checks if the form has any validation errors. Source: FormStructure.ts:222
returns
boolean
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
id
string
required
The control ID to add validators to
validators
Validator
required
ValidatorFn, ValidatorFn[], or null

addAsyncValidators

addAsyncValidators(id: string, validators: AsyncValidator): void
Adds asynchronous validators to a specific control. Source: FormStructure.ts:344
id
string
required
The control ID to add validators to
validators
AsyncValidator
required
AsyncValidatorFn, AsyncValidatorFn[], or null

setValidator

setValidator(id: string, validators: Validator): void
Replaces all synchronous validators on a control. Source: FormStructure.ts:356
id
string
required
The control ID to set validators for
validators
Validator
required
ValidatorFn, ValidatorFn[], or null

setAsyncValidator

setAsyncValidator(id: string, validators: AsyncValidator): void
Replaces all asynchronous validators on a control. Source: FormStructure.ts:370
id
string
required
The control ID to set validators for
validators
AsyncValidator
required
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
from
number
required
The index position to insert nodes at
nodes
Node[]
required
Array of nodes to insert

removeNodes

removeNodes(nodes: Node[]): void
Removes multiple nodes from the form. Source: FormStructure.ts:243
nodes
Node[]
required
Array of nodes to remove

createFormControl

createFormControl(node: Node): void
Creates or updates a form control for a given node. Source: FormStructure.ts:293
node
Node
required
The node to create a control for

removeFormControl

removeFormControl(node: Node): void
Removes a form control from the FormGroup. Source: FormStructure.ts:284
node
Node
required
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
from
number
required
The index position to insert buttons at
nodes
Button[]
required
Array of button nodes to insert

removeValidateActions

removeValidateActions(nodes: Button[]): void
Removes multiple action buttons from the form. Source: FormStructure.ts:266
nodes
Button[]
required
Array of button nodes to remove

Utility Methods

fromGroupSize

fromGroupSize(): number
Counts the total number of controls in the FormGroup. Source: FormStructure.ts:275
returns
number
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
node
Node
required
The node to attach events to

Usage Examples

Basic Form Creation

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();

Dynamic Form Manipulation

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)

isInalid(): boolean
Deprecated since: v1.4.0
Removed in: v1.5.0
Use instead: isInvalid

Build docs developers (and LLMs) love