@ng-forge/dynamic-form-mcp 0.5.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,7 +18,7 @@ var require_docs = __commonJS({
18
18
  id: "advanced-events",
19
19
  title: "Advanced Events",
20
20
  category: "advanced",
21
- content: "The event bus enables communication between the `dynamic-form` component and custom field components within it. Each form instance has its own isolated event bus.\n\n## Overview\n\nThe event bus provides:\n\n- Communication between field components within a single form\n- Type-safe event subscriptions\n- Reactive event handling with RxJS\n- Wizard page navigation coordination\n- Custom field component workflows\n\n**Note**: The event bus is scoped to each `dynamic-form` instance - events don't cross form boundaries.\n\n## Usage in Custom Field Components\n\nWhen building custom field types, inject the event bus to communicate with the parent form or other fields:\n\n```typescript\nimport { Component, inject } from '@angular/core';\nimport { EventBus } from '@ng-forge/dynamic-forms';\n\n@Component({\n selector: 'app-custom-submit-button',\n template: `<button (click)=\"submit()\">Submit Form</button>`,\n})\nexport class CustomSubmitButton {\n eventBus = inject(EventBus);\n\n submit() {\n // Dispatch submit event to the parent dynamic-forms\n this.eventBus.dispatch(SubmitEvent);\n }\n}\n```\n\n## Built-in Events\n\n### SubmitEvent\n\nFired when form is submitted.\n\n```typescript\neventBus.on<SubmitEvent>('submit').subscribe(() => {\n // Handle form submission\n console.log('Form submitted');\n});\n```\n\n### PageChangeEvent\n\nFired when navigating between wizard pages.\n\n```typescript\neventBus.on<PageChangeEvent>('page-change').subscribe((event) => {\n console.log(`Page ${event.currentPageIndex + 1} of ${event.totalPages}`);\n console.log(`Previous page: ${event.previousPageIndex}`);\n});\n```\n\n**Properties:**\n\n- `currentPageIndex: number` - Current page (0-based)\n- `totalPages: number` - Total number of pages\n- `previousPageIndex?: number` - Previous page index\n\n### NextPageEvent\n\nNavigate to next page in wizard.\n\n```typescript\neventBus.dispatch(NextPageEvent);\n```\n\n### PreviousPageEvent\n\nNavigate to previous page in wizard.\n\n```typescript\neventBus.dispatch(PreviousPageEvent);\n```\n\n### FormResetEvent\n\nReset form to default values.\n\n```typescript\n// Dispatch reset event\neventBus.dispatch(FormResetEvent);\n\n// Listen for reset\neventBus.on<FormResetEvent>('form-reset').subscribe(() => {\n console.log('Form was reset to defaults');\n});\n```\n\n### FormClearEvent\n\nClear all form values (empty state, not defaults).\n\n```typescript\n// Dispatch clear event\neventBus.dispatch(FormClearEvent);\n\n// Listen for clear\neventBus.on<FormClearEvent>('form-clear').subscribe(() => {\n console.log('Form was cleared');\n});\n```\n\n### AddArrayItemEvent\n\nAdd an item to an array field.\n\n```typescript\n// Add item using array's template\neventBus.dispatch(AddArrayItemEvent, 'contacts');\n\n// Add item with custom field template\nconst fieldTemplate = { key: 'email', type: 'input', value: '' };\neventBus.dispatch(AddArrayItemEvent, 'contacts', fieldTemplate);\n\n// Add item at specific index\neventBus.dispatch(AddArrayItemEvent, 'contacts', fieldTemplate, 2);\n```\n\n**Constructor parameters:**\n\n- `arrayKey: string` - Key of the array field\n- `field?: ArrayAllowedChildren` - Optional field template (uses array's template if omitted)\n- `index?: number` - Optional index to insert at (defaults to end)\n\n### RemoveArrayItemEvent\n\nRemove an item from an array field.\n\n```typescript\n// Remove item at index 1\neventBus.dispatch(RemoveArrayItemEvent, 'contacts', 1);\n\n// Remove last item\neventBus.dispatch(RemoveArrayItemEvent, 'contacts');\n```\n\n**Constructor parameters:**\n\n- `arrayKey: string` - Key of the array field\n- `index?: number` - Index to remove (defaults to last item)\n\n## Multiple Event Subscriptions\n\nSubscribe to multiple event types by passing an array of type strings:\n\n```typescript\neventBus.on<SubmitEvent | PageChangeEvent | NextPageEvent>(['submit', 'page-change', 'next-page']).subscribe((event) => {\n switch (event.type) {\n case 'submit':\n handleSubmit();\n break;\n case 'page-change':\n handlePageChange(event);\n break;\n case 'next-page':\n handleNextPage();\n break;\n }\n});\n```\n\n## Custom Events\n\nCreate custom events for your forms:\n\n```typescript\nimport { FormEvent } from '@ng-forge/dynamic-forms';\n\n// Simple event\nexport class SaveDraftEvent implements FormEvent {\n readonly type = 'save-draft' as const;\n}\n\n// Event with payload\nexport class ValidationErrorEvent implements FormEvent {\n readonly type = 'validation-error' as const;\n\n constructor(\n public readonly fieldKey: string,\n public readonly errorMessage: string,\n ) {}\n}\n```\n\nUsage:\n\n```typescript\n// Dispatch simple event\neventBus.dispatch(SaveDraftEvent);\n\n// Dispatch event with payload\neventBus.dispatch(ValidationErrorEvent, 'email', 'Invalid email format');\n\n// Subscribe to custom event\neventBus.on<SaveDraftEvent>('save-draft').subscribe(() => {\n saveDraft();\n});\n\neventBus.on<ValidationErrorEvent>('validation-error').subscribe((event) => {\n showError(event.fieldKey, event.errorMessage);\n});\n```\n\n## Practical Examples\n\n### Form Auto-save\n\n```typescript\n@Component({...})\nexport class AutoSaveFormComponent {\n eventBus = inject(EventBus);\n\n ngOnInit() {\n // Auto-save on page change\n this.eventBus.on<PageChangeEvent>('page-change').subscribe(() => {\n this.saveDraft();\n });\n }\n\n saveDraft() {\n // Save form data\n }\n}\n```\n\n### Multi-step Form Navigation\n\n```typescript\n@Component({\n template: `\n <button (click)=\"previous()\">Previous</button>\n <button (click)=\"next()\">Next</button>\n <button (click)=\"submit()\">Submit</button>\n `,\n})\nexport class WizardNavigationComponent {\n eventBus = inject(EventBus);\n\n previous() {\n this.eventBus.dispatch(PreviousPageEvent);\n }\n\n next() {\n this.eventBus.dispatch(NextPageEvent);\n }\n\n submit() {\n this.eventBus.dispatch(SubmitEvent);\n }\n}\n```\n\n### Progress Tracking\n\n```typescript\n@Component({...})\nexport class ProgressTrackerComponent {\n eventBus = inject(EventBus);\n progress = signal(0);\n\n ngOnInit() {\n this.eventBus.on<PageChangeEvent>('page-change').subscribe((event) => {\n const percentage = ((event.currentPageIndex + 1) / event.totalPages) * 100;\n this.progress.set(percentage);\n });\n }\n}\n```\n\n### Form Reset and Clear\n\n```typescript\n@Component({...})\nexport class FormActionsComponent {\n eventBus = inject(EventBus);\n\n resetForm() {\n // Reset form to default values\n this.eventBus.dispatch(FormResetEvent);\n }\n\n clearForm() {\n // Clear all form values\n this.eventBus.dispatch(FormClearEvent);\n }\n}\n```\n\n## Best Practices\n\n**Use built-in events:**\n\n- Leverage existing events for common scenarios\n- Consistent behavior across forms\n\n**Create custom events for domain logic:**\n\n- Keep event names descriptive\n- Include necessary payload data\n- Use readonly properties\n\n**Type safety:**\n\n```typescript\n// \u2713 Type-safe event subscription\nclass UserUpdatedEvent implements FormEvent {\n readonly type = 'user-updated' as const;\n constructor(public readonly userId: string) {}\n}\n\n// \u2713 Use generic parameter for type inference\neventBus.on<UserUpdatedEvent>('user-updated').subscribe((event) => {\n console.log(event.userId); // TypeScript knows event has userId\n});\n\n// \u2717 Avoid subscriptions without generic type parameter\neventBus.on('some-random-event'); // No type checking on event properties\n```\n\n## Attaching Form Values to Events\n\nBy default, events don't include the form's current value. You can opt-in to automatically attach the form value to all dispatched events using `withEventFormValue()`.\n\n### Global Opt-in\n\nEnable for all forms in your application:\n\n```typescript\nimport { provideDynamicForm, withEventFormValue } from '@ng-forge/dynamic-forms';\n\nprovideDynamicForm(...withMaterialFields(), withEventFormValue());\n```\n\n### Per-Form Control\n\nOverride the global setting for specific forms:\n\n```typescript\nconst config: FormConfig = {\n fields: [...],\n options: {\n // Enable for this form (even if globally disabled)\n emitFormValueOnEvents: true,\n // Or disable for this form (even if globally enabled)\n // emitFormValueOnEvents: false,\n }\n};\n```\n\n### Accessing the Form Value\n\nUse the `hasFormValue()` type guard to safely access the attached value:\n\n```typescript\nimport { hasFormValue } from '@ng-forge/dynamic-forms';\n\neventBus.on<SubmitEvent>('submit').subscribe((event) => {\n if (hasFormValue(event)) {\n // TypeScript knows event.formValue exists\n console.log('Form value at submission:', event.formValue);\n sendToApi(event.formValue);\n }\n});\n```\n\nThis is useful when you need the complete form state at the time an event occurred, such as:\n\n- Logging form values on submission\n- Auto-saving on page changes\n- Analytics tracking\n\n## Event Flow\n\n1. Component dispatches event via `eventBus.dispatch()`\n2. Event bus broadcasts to all subscribers\n3. Subscribers receive event and execute handlers\n4. Type filtering ensures only relevant handlers execute\n\n## Integration with Forms\n\nThe event bus is automatically provided by the `DynamicForm` component to all child field components. You don't need to manually provide it:\n\n```typescript\n// The DynamicForm component internally provides EventBus\n// All child field components can inject and use it\nimport { DynamicForm } from '@ng-forge/dynamic-forms';\n\n@Component({\n selector: 'app-my-form',\n imports: [DynamicForm],\n template: `<form [dynamic-form]=\"config\"></form>`,\n})\nexport class MyFormComponent {\n // EventBus is available to all field components rendered by DynamicForm\n}\n```\n\nField components can inject and use the event bus:\n\n```typescript\nexport class CustomFieldComponent extends BaseFieldComponent {\n eventBus = inject(EventBus);\n\n onSubmit() {\n // Trigger form submission from custom component\n this.eventBus.dispatch(SubmitEvent);\n }\n}\n```"
21
+ content: "The event bus enables communication between the `dynamic-form` component and custom field components within it. Each form instance has its own isolated event bus.\n\n## Overview\n\nThe event bus provides:\n\n- Communication between field components within a single form\n- Type-safe event subscriptions\n- Reactive event handling with RxJS\n- Wizard page navigation coordination\n- Custom field component workflows\n\n**Note**: The event bus is scoped to each `dynamic-form` instance - events don't cross form boundaries.\n\n## Usage in Custom Field Components\n\nWhen building custom field types, inject the event bus to communicate with the parent form or other fields:\n\n```typescript\nimport { Component, inject } from '@angular/core';\nimport { EventBus } from '@ng-forge/dynamic-forms';\n\n@Component({\n selector: 'app-custom-submit-button',\n template: `<button (click)=\"submit()\">Submit Form</button>`,\n})\nexport class CustomSubmitButton {\n eventBus = inject(EventBus);\n\n submit() {\n // Dispatch submit event to the parent dynamic-forms\n this.eventBus.dispatch(SubmitEvent);\n }\n}\n```\n\n## Built-in Events\n\n### SubmitEvent\n\nFired when form is submitted.\n\n```typescript\neventBus.on<SubmitEvent>('submit').subscribe(() => {\n // Handle form submission\n console.log('Form submitted');\n});\n```\n\n### PageChangeEvent\n\nFired when navigating between wizard pages.\n\n```typescript\neventBus.on<PageChangeEvent>('page-change').subscribe((event) => {\n console.log(`Page ${event.currentPageIndex + 1} of ${event.totalPages}`);\n console.log(`Previous page: ${event.previousPageIndex}`);\n});\n```\n\n**Properties:**\n\n- `currentPageIndex: number` - Current page (0-based)\n- `totalPages: number` - Total number of pages\n- `previousPageIndex?: number` - Previous page index\n\n### NextPageEvent\n\nNavigate to next page in wizard.\n\n```typescript\neventBus.dispatch(NextPageEvent);\n```\n\n### PreviousPageEvent\n\nNavigate to previous page in wizard.\n\n```typescript\neventBus.dispatch(PreviousPageEvent);\n```\n\n### FormResetEvent\n\nReset form to default values.\n\n```typescript\n// Dispatch reset event\neventBus.dispatch(FormResetEvent);\n\n// Listen for reset\neventBus.on<FormResetEvent>('form-reset').subscribe(() => {\n console.log('Form was reset to defaults');\n});\n```\n\n### FormClearEvent\n\nClear all form values (empty state, not defaults).\n\n```typescript\n// Dispatch clear event\neventBus.dispatch(FormClearEvent);\n\n// Listen for clear\neventBus.on<FormClearEvent>('form-clear').subscribe(() => {\n console.log('Form was cleared');\n});\n```\n\n### Array Events\n\nThe `arrayEvent()` builder provides a fluent API for array field manipulation. Import it from the main package:\n\n```typescript\nimport { arrayEvent } from '@ng-forge/dynamic-forms';\n```\n\n#### Adding Items\n\n**Important:** A template is required for all add operations. The template defines the structure of the new item:\n\n- **Single FieldDef** \u2192 creates a **primitive item** (field value extracted directly)\n- **Array of FieldDefs** \u2192 creates an **object item** (fields merged into object)\n\n```typescript\n// Define templates\nconst tagTemplate = { key: 'tag', type: 'input', label: 'Tag' }; // Primitive item\nconst contactTemplate = [\n // Object item\n { key: 'name', type: 'input', label: 'Name' },\n { key: 'email', type: 'input', label: 'Email' },\n];\n\n// Append item at end (most common)\neventBus.dispatch(arrayEvent('tags').append(tagTemplate)); // Primitive: adds a string value\neventBus.dispatch(arrayEvent('contacts').append(contactTemplate)); // Object: adds { name, email }\n\n// Prepend item at beginning\neventBus.dispatch(arrayEvent('contacts').prepend(contactTemplate));\n\n// Insert at specific index\neventBus.dispatch(arrayEvent('contacts').insertAt(2, contactTemplate));\n```\n\n#### Removing Items\n\n```typescript\n// Remove last item (stack pop)\neventBus.dispatch(arrayEvent('contacts').pop());\n\n// Remove first item (queue shift)\neventBus.dispatch(arrayEvent('contacts').shift());\n\n// Remove item at specific index\neventBus.dispatch(arrayEvent('contacts').removeAt(2));\n```\n\n#### Internal Event Classes\n\nFor advanced use cases (extending events or type-checking), you can import the underlying event classes:\n\n```typescript\nimport {\n AppendArrayItemEvent,\n PrependArrayItemEvent,\n InsertArrayItemEvent,\n PopArrayItemEvent,\n ShiftArrayItemEvent,\n RemoveAtIndexEvent,\n} from '@ng-forge/dynamic-forms';\n\n// Example: extend for custom template\nexport class AddContactEvent extends AppendArrayItemEvent {\n constructor() {\n super('contacts', [\n { key: 'name', type: 'input', label: 'Name' },\n { key: 'phone', type: 'input', label: 'Phone' },\n ]);\n }\n}\n\n// Usage\neventBus.dispatch(new AddContactEvent());\n```\n\n**Event types:**\n\n| Event | Description |\n| ----------------------- | ------------------------------ |\n| `AppendArrayItemEvent` | Add item at end of array |\n| `PrependArrayItemEvent` | Add item at beginning of array |\n| `InsertArrayItemEvent` | Add item at specific index |\n| `PopArrayItemEvent` | Remove last item |\n| `ShiftArrayItemEvent` | Remove first item |\n| `RemoveAtIndexEvent` | Remove item at specific index |\n\n## Multiple Event Subscriptions\n\nSubscribe to multiple event types by passing an array of type strings:\n\n```typescript\neventBus.on<SubmitEvent | PageChangeEvent | NextPageEvent>(['submit', 'page-change', 'next-page']).subscribe((event) => {\n switch (event.type) {\n case 'submit':\n handleSubmit();\n break;\n case 'page-change':\n handlePageChange(event);\n break;\n case 'next-page':\n handleNextPage();\n break;\n }\n});\n```\n\n## Custom Events\n\nCreate custom events for your forms:\n\n```typescript\nimport { FormEvent } from '@ng-forge/dynamic-forms';\n\n// Simple event\nexport class SaveDraftEvent implements FormEvent {\n readonly type = 'save-draft' as const;\n}\n\n// Event with payload\nexport class ValidationErrorEvent implements FormEvent {\n readonly type = 'validation-error' as const;\n\n constructor(\n public readonly fieldKey: string,\n public readonly errorMessage: string,\n ) {}\n}\n```\n\nUsage:\n\n```typescript\n// Dispatch simple event\neventBus.dispatch(SaveDraftEvent);\n\n// Dispatch event with payload\neventBus.dispatch(ValidationErrorEvent, 'email', 'Invalid email format');\n\n// Subscribe to custom event\neventBus.on<SaveDraftEvent>('save-draft').subscribe(() => {\n saveDraft();\n});\n\neventBus.on<ValidationErrorEvent>('validation-error').subscribe((event) => {\n showError(event.fieldKey, event.errorMessage);\n});\n```\n\n## Practical Examples\n\n### Form Auto-save\n\n```typescript\n@Component({...})\nexport class AutoSaveFormComponent {\n eventBus = inject(EventBus);\n\n ngOnInit() {\n // Auto-save on page change\n this.eventBus.on<PageChangeEvent>('page-change').subscribe(() => {\n this.saveDraft();\n });\n }\n\n saveDraft() {\n // Save form data\n }\n}\n```\n\n### Multi-step Form Navigation\n\n```typescript\n@Component({\n template: `\n <button (click)=\"previous()\">Previous</button>\n <button (click)=\"next()\">Next</button>\n <button (click)=\"submit()\">Submit</button>\n `,\n})\nexport class WizardNavigationComponent {\n eventBus = inject(EventBus);\n\n previous() {\n this.eventBus.dispatch(PreviousPageEvent);\n }\n\n next() {\n this.eventBus.dispatch(NextPageEvent);\n }\n\n submit() {\n this.eventBus.dispatch(SubmitEvent);\n }\n}\n```\n\n### Progress Tracking\n\n```typescript\n@Component({...})\nexport class ProgressTrackerComponent {\n eventBus = inject(EventBus);\n progress = signal(0);\n\n ngOnInit() {\n this.eventBus.on<PageChangeEvent>('page-change').subscribe((event) => {\n const percentage = ((event.currentPageIndex + 1) / event.totalPages) * 100;\n this.progress.set(percentage);\n });\n }\n}\n```\n\n### Form Reset and Clear\n\n```typescript\n@Component({...})\nexport class FormActionsComponent {\n eventBus = inject(EventBus);\n\n resetForm() {\n // Reset form to default values\n this.eventBus.dispatch(FormResetEvent);\n }\n\n clearForm() {\n // Clear all form values\n this.eventBus.dispatch(FormClearEvent);\n }\n}\n```\n\n## Best Practices\n\n**Use built-in events:**\n\n- Leverage existing events for common scenarios\n- Consistent behavior across forms\n\n**Create custom events for domain logic:**\n\n- Keep event names descriptive\n- Include necessary payload data\n- Use readonly properties\n\n**Type safety:**\n\n```typescript\n// \u2713 Type-safe event subscription\nclass UserUpdatedEvent implements FormEvent {\n readonly type = 'user-updated' as const;\n constructor(public readonly userId: string) {}\n}\n\n// \u2713 Use generic parameter for type inference\neventBus.on<UserUpdatedEvent>('user-updated').subscribe((event) => {\n console.log(event.userId); // TypeScript knows event has userId\n});\n\n// \u2717 Avoid subscriptions without generic type parameter\neventBus.on('some-random-event'); // No type checking on event properties\n```\n\n## Attaching Form Values to Events\n\nBy default, events don't include the form's current value. You can opt-in to automatically attach the form value to all dispatched events using `withEventFormValue()`.\n\n### Global Opt-in\n\nEnable for all forms in your application:\n\n```typescript\nimport { provideDynamicForm, withEventFormValue } from '@ng-forge/dynamic-forms';\n\nprovideDynamicForm(...withMaterialFields(), withEventFormValue());\n```\n\n### Per-Form Control\n\nOverride the global setting for specific forms:\n\n```typescript\nconst config: FormConfig = {\n fields: [...],\n options: {\n // Enable for this form (even if globally disabled)\n emitFormValueOnEvents: true,\n // Or disable for this form (even if globally enabled)\n // emitFormValueOnEvents: false,\n }\n};\n```\n\n### Accessing the Form Value\n\nUse the `hasFormValue()` type guard to safely access the attached value:\n\n```typescript\nimport { hasFormValue } from '@ng-forge/dynamic-forms';\n\neventBus.on<SubmitEvent>('submit').subscribe((event) => {\n if (hasFormValue(event)) {\n // TypeScript knows event.formValue exists\n console.log('Form value at submission:', event.formValue);\n sendToApi(event.formValue);\n }\n});\n```\n\nThis is useful when you need the complete form state at the time an event occurred, such as:\n\n- Logging form values on submission\n- Auto-saving on page changes\n- Analytics tracking\n\n## Event Flow\n\n1. Component dispatches event via `eventBus.dispatch()`\n2. Event bus broadcasts to all subscribers\n3. Subscribers receive event and execute handlers\n4. Type filtering ensures only relevant handlers execute\n\n## Integration with Forms\n\nThe event bus is automatically provided by the `DynamicForm` component to all child field components. You don't need to manually provide it:\n\n```typescript\n// The DynamicForm component internally provides EventBus\n// All child field components can inject and use it\nimport { DynamicForm } from '@ng-forge/dynamic-forms';\n\n@Component({\n selector: 'app-my-form',\n imports: [DynamicForm],\n template: `<form [dynamic-form]=\"config\"></form>`,\n})\nexport class MyFormComponent {\n // EventBus is available to all field components rendered by DynamicForm\n}\n```\n\nField components can inject and use the event bus:\n\n```typescript\nexport class CustomFieldComponent extends BaseFieldComponent {\n eventBus = inject(EventBus);\n\n onSubmit() {\n // Trigger form submission from custom component\n this.eventBus.dispatch(SubmitEvent);\n }\n}\n```"
22
22
  },
23
23
  {
24
24
  id: "advanced-expression-parser",
@@ -36,7 +36,7 @@ var require_docs = __commonJS({
36
36
  id: "ai-integration",
37
37
  title: "AI Integration",
38
38
  category: "ai-integration",
39
- content: '# AI Integration\n\nThe `@ng-forge/dynamic-form-mcp` package provides a [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server that enables AI assistants to generate, validate, and work with ng-forge dynamic form configurations.\n\n## Available Tools\n\nThe MCP server provides 4 focused tools:\n\n| Tool | Description | Read-only |\n| ------------------ | ----------------------------------------------------------- | --------- |\n| `ngforge_lookup` | Get documentation about field types, concepts, and patterns | \u2705 |\n| `ngforge_examples` | Get working code examples for common form patterns | \u2705 |\n| `ngforge_validate` | Validate FormConfig and get detailed error feedback | \u2705 |\n| `ngforge_scaffold` | Generate valid FormConfig skeletons | \u2705 |\n\n## Get Started\n\n### Cursor\n\nAdd to your Cursor MCP settings:\n\n```json\n{\n "ng-forge": {\n "command": "npx",\n "args": ["-y", "@ng-forge/dynamic-form-mcp"]\n }\n}\n```\n\n### VS Code with Copilot\n\nCreate `.vscode/mcp.json` in your project:\n\n```json\n{\n "servers": {\n "ng-forge": {\n "command": "npx",\n "args": ["-y", "@ng-forge/dynamic-form-mcp"]\n }\n }\n}\n```\n\n### Claude Desktop\n\nAdd to `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS):\n\n```json\n{\n "mcpServers": {\n "ng-forge": {\n "command": "npx",\n "args": ["-y", "@ng-forge/dynamic-form-mcp"]\n }\n }\n}\n```\n\n### JetBrains IDEs\n\nGo to **Settings > Tools > AI Assistant > Model Context Protocol (MCP)** and add:\n\n| Field | Value |\n| --------- | ----------------------------- |\n| Name | ng-forge |\n| Command | npx |\n| Arguments | -y @ng-forge/dynamic-form-mcp |\n\n------------ | --------------------------------------------------------- | ---------- | ----------------------- |\n| `topic` | string | (required) | Topic to look up |\n| `depth` | `"brief"` \\| `"full"` \\| `"schema"` | `"full"` | Level of detail |\n| `uiIntegration` | `"material"` \\| `"bootstrap"` \\| `"primeng"` \\| `"ionic"` | - | Filter UI-specific info |\n\n**Available Topics:**\n\n| Category | Topics |\n| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Field Types | `input`, `select`, `radio`, `checkbox`, `textarea`, `datepicker`, `slider`, `toggle`, `hidden`, `text`, `button`, `submit`, `next`, `previous`, `addArrayItem`, `removeArrayItem` |\n| Containers | `group`, `row`, `array`, `page` |\n| Concepts | `validation`, `conditional`, `derivation`, `options-format`, `expression-variables`, `async-validators`, `validation-messages` |\n| Patterns | `golden-path`, `multi-page-gotchas`, `pitfalls`, `workflow` |\n\n**Examples:**\n\n```\nngforge_lookup topic="hidden" depth="brief"\nngforge_lookup topic="conditional" depth="full"\nngforge_lookup topic="input" depth="schema" uiIntegration="material"\n```\n\n---\n\n### ngforge_examples\n\nGet working code examples for common patterns.\n\n| Parameter | Type | Default | Description |\n| --------- | ----------------------------------------------------- | ---------- | --------------- |\n| `pattern` | string | (required) | Pattern name |\n| `depth` | `"minimal"` \\| `"brief"` \\| `"full"` \\| `"explained"` | `"full"` | Level of detail |\n\n**Available Patterns:**\n\n| Pattern | Description | Lines |\n| --------------------- | ---------------------------------------- | ----- |\n| `minimal-multipage` | Simplest 2-page wizard form | ~50 |\n| `minimal-array` | Array with add/remove buttons | ~30 |\n| `minimal-conditional` | Show/hide field based on condition | ~25 |\n| `minimal-validation` | Password confirmation validation | ~20 |\n| `minimal-hidden` | Hidden fields in multi-page form | ~15 |\n| `derivation` | Value derivation (computed fields) | - |\n| `conditional` | Conditional visibility patterns | - |\n| `multi-page` | Multi-step wizard forms | - |\n| `validation` | Form validation patterns | - |\n| `complete` | Full form with all major features | - |\n| `mega` | Kitchen sink demonstrating every feature | - |\n\n**Examples:**\n\n```\nngforge_examples pattern="minimal-multipage" depth="minimal"\nngforge_examples pattern="conditional" depth="explained"\n```\n\n---\n\n### ngforge_validate\n\nValidate FormConfig and get detailed error feedback.\n\n| Parameter | Type | Default | Description |\n| --------------- | --------------------------------------------------------- | ------------ | ------------------------------ |\n| `config` | string \\| object | (required) | File path or JSON config |\n| `uiIntegration` | `"material"` \\| `"bootstrap"` \\| `"primeng"` \\| `"ionic"` | `"material"` | UI library to validate against |\n\n**Input Detection:**\n\n| Input | Treated As |\n| ------------------------ | ------------------ |\n| Ends with `.ts` or `.js` | File path |\n| Starts with `{` or `[` | JSON string |\n| Object | Validated directly |\n\n**Example Errors:**\n\n- "Hidden field missing REQUIRED value property"\n- "options MUST be at FIELD level, NOT inside props"\n- "row containers do NOT support logic blocks"\n\n**Examples:**\n\n```\nngforge_validate config="/path/to/form.config.ts"\nngforge_validate config=\'{"fields":[...]}\' uiIntegration="bootstrap"\n```\n\n---\n\n### ngforge_scaffold\n\nGenerate valid FormConfig skeletons.\n\n| Parameter | Type | Default | Description |\n| --------------- | -------- | ------------ | ------------------------------------- |\n| `pages` | number | `0` | Number of pages (0 = single-page) |\n| `arrays` | string[] | `[]` | Array field names |\n| `groups` | string[] | `[]` | Group field names |\n| `hidden` | string[] | `[]` | Hidden fields as `"name:value"` pairs |\n| `fields` | string[] | `[]` | Fields as `"name:type"` pairs |\n| `uiIntegration` | enum | `"material"` | UI library |\n\n**Supported Types for `fields`:**\n\n`input`, `select`, `radio`, `checkbox`, `textarea`, `datepicker`, `slider`, `toggle`\n\n**Examples:**\n\n```\nngforge_scaffold pages=0 fields=["name:input","email:input"]\nngforge_scaffold pages=3 arrays=["contacts"] groups=["address"]\nngforge_scaffold hidden=["userId:abc123","source:web"]\n```\n\n---\n\n## MCP Resources\n\nIn addition to tools, the server exposes resources that AI can read:\n\n| Resource URI | Description |\n| -------------------------- | ---------------------------------------------- |\n| `ng-forge://instructions` | Best practices guide for generating FormConfig |\n| `ng-forge://examples` | Curated FormConfig examples |\n| `ng-forge://examples/{id}` | Specific example by ID |\n| `ng-forge://field-types` | Field type reference |\n| `ng-forge://validators` | Validator reference |\n| `ng-forge://ui-adapters` | UI library configurations |\n| `ng-forge://docs` | Full documentation index |\n\n---\n\n## Feedback\n\nFound an issue or have a suggestion? [Open an issue on GitHub](https://github.com/ng-forge/ng-forge/issues).'
39
+ content: '# AI Integration\n\nThe `@ng-forge/dynamic-form-mcp` package provides a [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server that enables AI assistants to generate, validate, and work with ng-forge dynamic form configurations.\n\n## Available Tools\n\nThe MCP server provides 4 focused tools:\n\n| Tool | Description | Read-only |\n| ------------------ | ----------------------------------------------------------- | --------- |\n| `ngforge_lookup` | Get documentation about field types, concepts, and patterns | \u2705 |\n| `ngforge_examples` | Get working code examples for common form patterns | \u2705 |\n| `ngforge_validate` | Validate FormConfig and get detailed error feedback | \u2705 |\n| `ngforge_scaffold` | Generate valid FormConfig skeletons | \u2705 |\n\n## Get Started\n\n### Cursor\n\nAdd to your Cursor MCP settings:\n\n```json\n{\n "ng-forge": {\n "command": "npx",\n "args": ["-y", "@ng-forge/dynamic-form-mcp"]\n }\n}\n```\n\n### VS Code with Copilot\n\nCreate `.vscode/mcp.json` in your project:\n\n```json\n{\n "servers": {\n "ng-forge": {\n "command": "npx",\n "args": ["-y", "@ng-forge/dynamic-form-mcp"]\n }\n }\n}\n```\n\n### Claude Desktop\n\nAdd to `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS):\n\n```json\n{\n "mcpServers": {\n "ng-forge": {\n "command": "npx",\n "args": ["-y", "@ng-forge/dynamic-form-mcp"]\n }\n }\n}\n```\n\n### JetBrains IDEs\n\nGo to **Settings > Tools > AI Assistant > Model Context Protocol (MCP)** and add:\n\n| Field | Value |\n| --------- | ----------------------------- |\n| Name | ng-forge |\n| Command | npx |\n| Arguments | -y @ng-forge/dynamic-form-mcp |\n\n------------ | --------------------------------------------------------- | ---------- | ----------------------- |\n| `topic` | string | (required) | Topic to look up |\n| `depth` | `"brief"` \\| `"full"` \\| `"schema"` | `"full"` | Level of detail |\n| `uiIntegration` | `"material"` \\| `"bootstrap"` \\| `"primeng"` \\| `"ionic"` | - | Filter UI-specific info |\n\n**Available Topics:**\n\n| Category | Topics |\n| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Field Types | `input`, `select`, `radio`, `checkbox`, `textarea`, `datepicker`, `slider`, `toggle`, `hidden`, `text`, `button`, `submit`, `next`, `previous`, `addArrayItem`, `prependArrayItem`, `insertArrayItem`, `removeArrayItem`, `popArrayItem`, `shiftArrayItem` |\n| Containers | `group`, `row`, `array`, `page` |\n| Concepts | `validation`, `conditional`, `derivation`, `options-format`, `expression-variables`, `async-validators`, `validation-messages` |\n| Patterns | `golden-path`, `multi-page-gotchas`, `pitfalls`, `workflow` |\n\n**Examples:**\n\n```\nngforge_lookup topic="hidden" depth="brief"\nngforge_lookup topic="conditional" depth="full"\nngforge_lookup topic="input" depth="schema" uiIntegration="material"\n```\n\n---\n\n### ngforge_examples\n\nGet working code examples for common patterns.\n\n| Parameter | Type | Default | Description |\n| --------- | ----------------------------------------------------- | ---------- | --------------- |\n| `pattern` | string | (required) | Pattern name |\n| `depth` | `"minimal"` \\| `"brief"` \\| `"full"` \\| `"explained"` | `"full"` | Level of detail |\n\n**Available Patterns:**\n\n| Pattern | Description | Lines |\n| --------------------- | ---------------------------------------- | ----- |\n| `minimal-multipage` | Simplest 2-page wizard form | ~50 |\n| `minimal-array` | Array with add/remove buttons | ~30 |\n| `minimal-conditional` | Show/hide field based on condition | ~25 |\n| `minimal-validation` | Password confirmation validation | ~20 |\n| `minimal-hidden` | Hidden fields in multi-page form | ~15 |\n| `derivation` | Value derivation (computed fields) | - |\n| `conditional` | Conditional visibility patterns | - |\n| `multi-page` | Multi-step wizard forms | - |\n| `validation` | Form validation patterns | - |\n| `complete` | Full form with all major features | - |\n| `mega` | Kitchen sink demonstrating every feature | - |\n\n**Examples:**\n\n```\nngforge_examples pattern="minimal-multipage" depth="minimal"\nngforge_examples pattern="conditional" depth="explained"\n```\n\n---\n\n### ngforge_validate\n\nValidate FormConfig and get detailed error feedback.\n\n| Parameter | Type | Default | Description |\n| --------------- | --------------------------------------------------------- | ------------ | ------------------------------ |\n| `config` | string \\| object | (required) | File path or JSON config |\n| `uiIntegration` | `"material"` \\| `"bootstrap"` \\| `"primeng"` \\| `"ionic"` | `"material"` | UI library to validate against |\n\n**Input Detection:**\n\n| Input | Treated As |\n| ------------------------ | ------------------ |\n| Ends with `.ts` or `.js` | File path |\n| Starts with `{` or `[` | JSON string |\n| Object | Validated directly |\n\n**Example Errors:**\n\n- "Hidden field missing REQUIRED value property"\n- "options MUST be at FIELD level, NOT inside props"\n- "row containers do NOT support logic blocks"\n\n**Examples:**\n\n```\nngforge_validate config="/path/to/form.config.ts"\nngforge_validate config=\'{"fields":[...]}\' uiIntegration="bootstrap"\n```\n\n---\n\n### ngforge_scaffold\n\nGenerate valid FormConfig skeletons.\n\n| Parameter | Type | Default | Description |\n| --------------- | -------- | ------------ | ------------------------------------- |\n| `pages` | number | `0` | Number of pages (0 = single-page) |\n| `arrays` | string[] | `[]` | Array field names |\n| `groups` | string[] | `[]` | Group field names |\n| `hidden` | string[] | `[]` | Hidden fields as `"name:value"` pairs |\n| `fields` | string[] | `[]` | Fields as `"name:type"` pairs |\n| `uiIntegration` | enum | `"material"` | UI library |\n\n**Supported Types for `fields`:**\n\n`input`, `select`, `radio`, `checkbox`, `textarea`, `datepicker`, `slider`, `toggle`\n\n**Examples:**\n\n```\nngforge_scaffold pages=0 fields=["name:input","email:input"]\nngforge_scaffold pages=3 arrays=["contacts"] groups=["address"]\nngforge_scaffold hidden=["userId:abc123","source:web"]\n```\n\n---\n\n## MCP Resources\n\nIn addition to tools, the server exposes resources that AI can read:\n\n| Resource URI | Description |\n| -------------------------- | ---------------------------------------------- |\n| `ng-forge://instructions` | Best practices guide for generating FormConfig |\n| `ng-forge://examples` | Curated FormConfig examples |\n| `ng-forge://examples/{id}` | Specific example by ID |\n| `ng-forge://field-types` | Field type reference |\n| `ng-forge://validators` | Validator reference |\n| `ng-forge://ui-adapters` | UI library configurations |\n| `ng-forge://docs` | Full documentation index |\n\n---\n\n## Feedback\n\nFound an issue or have a suggestion? [Open an issue on GitHub](https://github.com/ng-forge/ng-forge/issues).'
40
40
  },
41
41
  {
42
42
  id: "dynamic-behavior-conditional-logic-overview",
@@ -60,7 +60,13 @@ var require_docs = __commonJS({
60
60
  id: "dynamic-behavior-value-derivation-basics",
61
61
  title: "Dynamic Behavior Value Derivation Basics",
62
62
  category: "dynamic-behavior",
63
- content: "Automatically compute and set field values based on other form values. Derivations enable calculated fields, auto-fill patterns, and value transformations.\n\n## Quick Start\n\nDerivations are defined ON the field that receives the computed value (self-targeting).\n\n### Shorthand Syntax (Preferred)\n\n```typescript\n{\n key: 'total',\n type: 'input',\n label: 'Total',\n readonly: true,\n derivation: 'formValue.quantity * formValue.unitPrice',\n}\n```\n\n### Logic Block Syntax\n\n```typescript\n{\n key: 'total',\n type: 'input',\n label: 'Total',\n readonly: true,\n logic: [{\n type: 'derivation',\n expression: 'formValue.quantity * formValue.unitPrice',\n }],\n}\n```\n\nWhen `quantity` or `unitPrice` changes, `total` is automatically recalculated.\n\n## Derivation Types\n\n### Expression-Based\n\nUse JavaScript expressions with access to `formValue`:\n\n```typescript\n{\n key: 'fullName',\n type: 'input',\n label: 'Full Name',\n readonly: true,\n derivation: '(formValue.firstName || \"\") + \" \" + (formValue.lastName || \"\")',\n}\n```\n\n**Available variables:**\n\n- `formValue` - Object containing all form field values\n- `externalData` - External application state (when configured in FormConfig)\n\n### Static Value\n\nSet a constant value when a condition is met:\n\n```typescript\n{\n key: 'phonePrefix',\n type: 'input',\n label: 'Phone Prefix',\n readonly: true,\n logic: [{\n type: 'derivation',\n value: '+1',\n condition: {\n type: 'fieldValue',\n fieldPath: 'country',\n operator: 'equals',\n value: 'USA',\n },\n }],\n}\n```\n\n### Custom Function\n\nUse a registered function for complex logic:\n\n```typescript\n// In form config\ncustomFnConfig: {\n derivations: {\n calculateTax: (ctx) => ctx.formValue.subtotal * getTaxRate(ctx.formValue.state),\n },\n},\nfields: [\n {\n key: 'tax',\n type: 'input',\n readonly: true,\n logic: [{\n type: 'derivation',\n functionName: 'calculateTax',\n dependsOn: ['subtotal', 'state'],\n }],\n },\n],\n```\n\n## Trigger Timing\n\nControl when derivations evaluate:\n\n| Trigger | Description | Use Case |\n| ----------- | ------------------------------------- | ------------------------------------- |\n| `onChange` | Immediately on value change (default) | Computed totals, conditional prefixes |\n| `debounced` | After value stabilizes | Self-transforms, format masking |\n\n### Debounced Derivations\n\nUse `trigger: 'debounced'` for self-transforming fields to avoid interrupting the user while typing:\n\n```typescript\n{\n key: 'email',\n type: 'input',\n label: 'Email',\n logic: [{\n type: 'derivation',\n expression: 'formValue.email.toLowerCase()',\n trigger: 'debounced',\n debounceMs: 500, // optional, defaults to 500\n }],\n}\n```\n\nThe transformation applies after the user stops typing for 500ms.\n\n## Conditional Derivations\n\nOnly apply derivations when conditions are met:\n\n```typescript\n{\n key: 'currency',\n type: 'input',\n label: 'Currency',\n readonly: true,\n logic: [\n {\n type: 'derivation',\n value: 'USD',\n condition: {\n type: 'fieldValue',\n fieldPath: 'country',\n operator: 'equals',\n value: 'USA',\n },\n },\n {\n type: 'derivation',\n value: 'EUR',\n condition: {\n type: 'fieldValue',\n fieldPath: 'country',\n operator: 'equals',\n value: 'Germany',\n },\n },\n ],\n}\n```\n\nMultiple derivations on the same field are evaluated in order.\n\n## Dependencies\n\n### Automatic Detection\n\nFor expressions, dependencies are automatically extracted:\n\n```typescript\n{\n key: 'total',\n type: 'input',\n label: 'Total',\n readonly: true,\n derivation: 'formValue.quantity * formValue.unitPrice',\n // Automatically depends on: quantity, unitPrice\n}\n```\n\n### Explicit Dependencies\n\nFor custom functions, specify dependencies explicitly:\n\n```typescript\n{\n key: 'discount',\n type: 'input',\n label: 'Discount',\n readonly: true,\n logic: [{\n type: 'derivation',\n functionName: 'calculateDiscount',\n dependsOn: ['total', 'memberLevel'],\n }],\n}\n```\n\nWithout `dependsOn`, custom functions re-evaluate on any form change.\n\n## Complete Example\n\n```typescript\nconst orderForm = {\n fields: [\n {\n key: 'quantity',\n type: 'input',\n value: 1,\n label: 'Quantity',\n props: { type: 'number' },\n },\n {\n key: 'unitPrice',\n type: 'input',\n value: 10,\n label: 'Unit Price',\n props: { type: 'number' },\n },\n {\n key: 'subtotal',\n type: 'input',\n value: 0,\n label: 'Subtotal',\n readonly: true,\n derivation: 'formValue.quantity * formValue.unitPrice',\n },\n {\n key: 'tax',\n type: 'input',\n value: 0,\n label: 'Tax (10%)',\n readonly: true,\n derivation: 'formValue.subtotal * 0.1',\n },\n {\n key: 'total',\n type: 'input',\n value: 0,\n label: 'Total',\n readonly: true,\n derivation: 'formValue.subtotal + formValue.tax',\n },\n ],\n} as const satisfies FormConfig;\n```\n\n## Array Field Derivations\n\nInside arrays, `formValue` is scoped to the current array item:\n\n```typescript\n{\n key: 'lineItems',\n type: 'array',\n fields: [\n {\n key: 'itemRow',\n type: 'row',\n fields: [\n { key: 'quantity', type: 'input', label: 'Qty', value: 1 },\n { key: 'unitPrice', type: 'input', label: 'Price', value: 0 },\n {\n key: 'lineTotal',\n type: 'input',\n label: 'Total',\n value: 0,\n readonly: true,\n // formValue is scoped to the current array item\n derivation: 'formValue.quantity * formValue.unitPrice',\n },\n ],\n },\n ],\n}\n```\n\n### Accessing Root Form Value\n\nInside array items, `formValue` refers to the current array item. Use `rootFormValue` to access the entire form:\n\n```typescript\n{\n key: 'lineTotal',\n type: 'input',\n label: 'Total',\n readonly: true,\n // formValue = current array item { quantity, unitPrice }\n // rootFormValue = entire form { lineItems, discount, ... }\n derivation: 'formValue.quantity * formValue.unitPrice * (1 - rootFormValue.discount / 100)',\n}\n```\n\n## Debugging Derivations\n\nEnable derivation logging to troubleshoot issues:\n\n### Configuration\n\nConfigure derivation logging via `withLoggerConfig`:\n\n```typescript\n// In your providers\nprovideDynamicForm(...withMaterialFields(), withLoggerConfig({ derivations: 'verbose' }));\n\n// Or just summary level\nprovideDynamicForm(...withMaterialFields(), withLoggerConfig({ derivations: 'summary' }));\n```\n\n### Log Levels\n\n| Level | Output |\n| --------- | --------------------------------- |\n| `none` | No logging (default) |\n| `summary` | Cycle completion with counts |\n| `verbose` | Individual derivation evaluations |\n\n### Using debugName\n\nAdd names to derivations for easier identification in logs:\n\n```typescript\n{\n key: 'lineTotal',\n type: 'input',\n label: 'Total',\n readonly: true,\n logic: [{\n type: 'derivation',\n debugName: 'Calculate line total',\n expression: 'formValue.quantity * formValue.unitPrice',\n }],\n}\n```\n\n**Console output (verbose mode):**\n\n```\nDerivation - Starting cycle (onChange) with 5 derivation(s)\nDerivation - Iteration 1\nDerivation - Applied \"Calculate line total\" { field: 'lineTotal', newValue: 150 }\nDerivation - Skipped: phonePrefix (condition not met)\nDerivation - Cycle complete (onChange) { applied: 1, skipped: 4, errors: 0, iterations: 1 }\n```\n\n## Bidirectional Derivations\n\nCreate two-way bindings between fields:\n\n```typescript\n// Celsius to Fahrenheit\n{\n key: 'fahrenheit',\n type: 'input',\n value: 32,\n derivation: 'formValue.celsius * 9 / 5 + 32',\n}\n\n// Fahrenheit to Celsius\n{\n key: 'celsius',\n type: 'input',\n value: 0,\n derivation: '(formValue.fahrenheit - 32) * 5 / 9',\n}\n```\n\n### Cycle Detection\n\nThe system automatically detects derivation cycles and warns during development:\n\n```\nBidirectional derivation detected: celsius <-> fahrenheit\nBidirectional derivations stabilize via equality check.\n```\n\n### Floating-Point Precision\n\nBidirectional derivations stabilize when the computed value equals the current value. For floating-point operations, consider:\n\n1. **Rounding in expressions:**\n\n ```typescript\n derivation: 'Math.round(formValue.usd * exchangeRate * 100) / 100';\n ```\n\n2. **Using integers:** Store cents instead of dollars\n3. **One-way derivation:** If bidirectional isn't required\n\n## Derivation Processing\n\n### Evaluation Order\n\nDerivations are topologically sorted based on dependencies:\n\n```\nquantity \u2500\u2510\n \u251C\u2500\u2500 subtotal \u2500\u2510\nunitPrice \u2500\u2518 \u251C\u2500\u2500 total\n \u2502\n tax \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n```\n\nThis ensures `subtotal` is computed before `total`.\n\n### Iteration Limits\n\nTo prevent infinite loops, derivations are limited to 10 iterations per cycle. If exceeded:\n\n```\nDerivation - Max iterations reached (onChange).\nThis may indicate a loop in derivation logic.\n```\n\n## DerivationLogicConfig Interface\n\n```typescript\ninterface DerivationLogicConfig {\n /** Logic type identifier */\n type: 'derivation';\n\n /** Optional name for debugging */\n debugName?: string;\n\n /** When to evaluate: 'onChange' (default) or 'debounced' */\n trigger?: 'onChange' | 'debounced';\n\n /** Debounce duration in ms (default: 500) */\n debounceMs?: number;\n\n /** Static value to set */\n value?: unknown;\n\n /** JavaScript expression (has access to formValue) */\n expression?: string;\n\n /** Name of registered custom function */\n functionName?: string;\n\n /** Explicit field dependencies */\n dependsOn?: string[];\n\n /** Condition for when derivation applies */\n condition?: ConditionalExpression | boolean;\n}\n```\n\n## External Data in Derivations\n\nUse external application state in derivation expressions:\n\n```typescript\nconst config = {\n externalData: {\n discountRate: computed(() => pricingService.currentDiscount()),\n },\n fields: [\n {\n key: 'discountedPrice',\n type: 'input',\n label: 'Discounted Price',\n readonly: true,\n derivation: 'formValue.price * (1 - externalData.discountRate)',\n },\n ],\n} as const satisfies FormConfig;\n```\n\nExternal data values are reactively tracked - when signals change, derivations are re-evaluated.\n\n## Related\n\n- **[Conditional Logic](../conditional-logic/overview/)** - Control field visibility and state\n- **[Array Fields](../../prebuilt/form-arrays/)** - Working with array fields\n- **[Examples](/docs/examples)** - Real-world form patterns"
63
+ content: "Automatically compute and set field values based on other form values. Derivations enable calculated fields, auto-fill patterns, and value transformations.\n\n## Quick Start\n\nDerivations are defined ON the field that receives the computed value (self-targeting).\n\n### Shorthand Syntax (Preferred)\n\n```typescript\n{\n key: 'total',\n type: 'input',\n label: 'Total',\n readonly: true,\n derivation: 'formValue.quantity * formValue.unitPrice',\n}\n```\n\n### Logic Block Syntax\n\n```typescript\n{\n key: 'total',\n type: 'input',\n label: 'Total',\n readonly: true,\n logic: [{\n type: 'derivation',\n expression: 'formValue.quantity * formValue.unitPrice',\n }],\n}\n```\n\nWhen `quantity` or `unitPrice` changes, `total` is automatically recalculated.\n\n## Derivation Types\n\n### Expression-Based\n\nUse JavaScript expressions with access to `formValue`:\n\n```typescript\n{\n key: 'fullName',\n type: 'input',\n label: 'Full Name',\n readonly: true,\n derivation: '(formValue.firstName || \"\") + \" \" + (formValue.lastName || \"\")',\n}\n```\n\n**Available variables:**\n\n- `formValue` - Object containing all form field values\n- `externalData` - External application state (when configured in FormConfig)\n\n### Static Value\n\nSet a constant value when a condition is met:\n\n```typescript\n{\n key: 'phonePrefix',\n type: 'input',\n label: 'Phone Prefix',\n readonly: true,\n logic: [{\n type: 'derivation',\n value: '+1',\n condition: {\n type: 'fieldValue',\n fieldPath: 'country',\n operator: 'equals',\n value: 'USA',\n },\n }],\n}\n```\n\n### Custom Function\n\nUse a registered function for complex logic:\n\n```typescript\n// In form config\ncustomFnConfig: {\n derivations: {\n calculateTax: (ctx) => ctx.formValue.subtotal * getTaxRate(ctx.formValue.state),\n },\n},\nfields: [\n {\n key: 'tax',\n type: 'input',\n readonly: true,\n logic: [{\n type: 'derivation',\n functionName: 'calculateTax',\n dependsOn: ['subtotal', 'state'],\n }],\n },\n],\n```\n\n## Trigger Timing\n\nControl when derivations evaluate:\n\n| Trigger | Description | Use Case |\n| ----------- | ------------------------------------- | ------------------------------------- |\n| `onChange` | Immediately on value change (default) | Computed totals, conditional prefixes |\n| `debounced` | After value stabilizes | Self-transforms, format masking |\n\n### Debounced Derivations\n\nUse `trigger: 'debounced'` for self-transforming fields to avoid interrupting the user while typing:\n\n```typescript\n{\n key: 'email',\n type: 'input',\n label: 'Email',\n logic: [{\n type: 'derivation',\n expression: 'formValue.email.toLowerCase()',\n trigger: 'debounced',\n debounceMs: 500, // optional, defaults to 500\n }],\n}\n```\n\nThe transformation applies after the user stops typing for 500ms.\n\n## Conditional Derivations\n\nOnly apply derivations when conditions are met:\n\n```typescript\n{\n key: 'currency',\n type: 'input',\n label: 'Currency',\n readonly: true,\n logic: [\n {\n type: 'derivation',\n value: 'USD',\n condition: {\n type: 'fieldValue',\n fieldPath: 'country',\n operator: 'equals',\n value: 'USA',\n },\n },\n {\n type: 'derivation',\n value: 'EUR',\n condition: {\n type: 'fieldValue',\n fieldPath: 'country',\n operator: 'equals',\n value: 'Germany',\n },\n },\n ],\n}\n```\n\nMultiple derivations on the same field are evaluated in order.\n\n## Dependencies\n\n### Automatic Detection\n\nFor expressions, dependencies are automatically extracted:\n\n```typescript\n{\n key: 'total',\n type: 'input',\n label: 'Total',\n readonly: true,\n derivation: 'formValue.quantity * formValue.unitPrice',\n // Automatically depends on: quantity, unitPrice\n}\n```\n\n### Explicit Dependencies\n\nFor custom functions, specify dependencies explicitly:\n\n```typescript\n{\n key: 'discount',\n type: 'input',\n label: 'Discount',\n readonly: true,\n logic: [{\n type: 'derivation',\n functionName: 'calculateDiscount',\n dependsOn: ['total', 'memberLevel'],\n }],\n}\n```\n\nWithout `dependsOn`, custom functions re-evaluate on any form change.\n\n## Complete Example\n\n```typescript\nconst orderForm = {\n fields: [\n {\n key: 'quantity',\n type: 'input',\n value: 1,\n label: 'Quantity',\n props: { type: 'number' },\n },\n {\n key: 'unitPrice',\n type: 'input',\n value: 10,\n label: 'Unit Price',\n props: { type: 'number' },\n },\n {\n key: 'subtotal',\n type: 'input',\n value: 0,\n label: 'Subtotal',\n readonly: true,\n derivation: 'formValue.quantity * formValue.unitPrice',\n },\n {\n key: 'tax',\n type: 'input',\n value: 0,\n label: 'Tax (10%)',\n readonly: true,\n derivation: 'formValue.subtotal * 0.1',\n },\n {\n key: 'total',\n type: 'input',\n value: 0,\n label: 'Total',\n readonly: true,\n derivation: 'formValue.subtotal + formValue.tax',\n },\n ],\n} as const satisfies FormConfig;\n```\n\n## Array Field Derivations\n\nInside arrays, `formValue` is scoped to the current array item:\n\n```typescript\n{\n key: 'lineItems',\n type: 'array',\n fields: [\n {\n key: 'itemRow',\n type: 'row',\n fields: [\n { key: 'quantity', type: 'input', label: 'Qty', value: 1 },\n { key: 'unitPrice', type: 'input', label: 'Price', value: 0 },\n {\n key: 'lineTotal',\n type: 'input',\n label: 'Total',\n value: 0,\n readonly: true,\n // formValue is scoped to the current array item\n derivation: 'formValue.quantity * formValue.unitPrice',\n },\n ],\n },\n ],\n}\n```\n\n### Accessing Root Form Value\n\nInside array items, `formValue` refers to the current array item. Use `rootFormValue` to access the entire form:\n\n```typescript\n{\n key: 'lineTotal',\n type: 'input',\n label: 'Total',\n readonly: true,\n // formValue = current array item { quantity, unitPrice }\n // rootFormValue = entire form { lineItems, discount, ... }\n derivation: 'formValue.quantity * formValue.unitPrice * (1 - rootFormValue.discount / 100)',\n}\n```\n\n## Debugging Derivations\n\nEnable derivation logging to troubleshoot issues:\n\n### Configuration\n\nConfigure derivation logging via `withLoggerConfig`:\n\n```typescript\n// In your providers\nprovideDynamicForm(...withMaterialFields(), withLoggerConfig({ derivations: 'verbose' }));\n\n// Or just summary level\nprovideDynamicForm(...withMaterialFields(), withLoggerConfig({ derivations: 'summary' }));\n```\n\n### Log Levels\n\n| Level | Output |\n| --------- | --------------------------------- |\n| `none` | No logging (default) |\n| `summary` | Cycle completion with counts |\n| `verbose` | Individual derivation evaluations |\n\n### Using debugName\n\nAdd names to derivations for easier identification in logs:\n\n```typescript\n{\n key: 'lineTotal',\n type: 'input',\n label: 'Total',\n readonly: true,\n logic: [{\n type: 'derivation',\n debugName: 'Calculate line total',\n expression: 'formValue.quantity * formValue.unitPrice',\n }],\n}\n```\n\n**Console output (verbose mode):**\n\n```\nDerivation - Starting cycle (onChange) with 5 derivation(s)\nDerivation - Iteration 1\nDerivation - Applied \"Calculate line total\" { field: 'lineTotal', newValue: 150 }\nDerivation - Skipped: phonePrefix (condition not met)\nDerivation - Cycle complete (onChange) { applied: 1, skipped: 4, errors: 0, iterations: 1 }\n```\n\n## Bidirectional Derivations\n\nCreate two-way bindings between fields:\n\n```typescript\n// Celsius to Fahrenheit\n{\n key: 'fahrenheit',\n type: 'input',\n value: 32,\n derivation: 'formValue.celsius * 9 / 5 + 32',\n}\n\n// Fahrenheit to Celsius\n{\n key: 'celsius',\n type: 'input',\n value: 0,\n derivation: '(formValue.fahrenheit - 32) * 5 / 9',\n}\n```\n\n### Cycle Detection\n\nThe system automatically detects derivation cycles and warns during development:\n\n```\nBidirectional derivation detected: celsius <-> fahrenheit\nBidirectional derivations stabilize via equality check.\n```\n\n### Floating-Point Precision\n\nBidirectional derivations stabilize when the computed value equals the current value. For floating-point operations, consider:\n\n1. **Rounding in expressions:**\n\n ```typescript\n derivation: 'Math.round(formValue.usd * exchangeRate * 100) / 100';\n ```\n\n2. **Using integers:** Store cents instead of dollars\n3. **One-way derivation:** If bidirectional isn't required\n\n## Derivation Processing\n\n### Evaluation Order\n\nDerivations are topologically sorted based on dependencies:\n\n```\nquantity \u2500\u2510\n \u251C\u2500\u2500 subtotal \u2500\u2510\nunitPrice \u2500\u2518 \u251C\u2500\u2500 total\n \u2502\n tax \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n```\n\nThis ensures `subtotal` is computed before `total`.\n\n### Iteration Limits\n\nTo prevent infinite loops, derivations are limited to 10 iterations per cycle. If exceeded:\n\n```\nDerivation - Max iterations reached (onChange).\nThis may indicate a loop in derivation logic.\n```\n\n## DerivationLogicConfig Interface\n\n```typescript\ninterface DerivationLogicConfig {\n /** Logic type identifier */\n type: 'derivation';\n\n /** Optional name for debugging */\n debugName?: string;\n\n /** When to evaluate: 'onChange' (default) or 'debounced' */\n trigger?: 'onChange' | 'debounced';\n\n /** Debounce duration in ms (default: 500) */\n debounceMs?: number;\n\n /** Static value to set */\n value?: unknown;\n\n /** JavaScript expression (has access to formValue) */\n expression?: string;\n\n /** Name of registered custom function */\n functionName?: string;\n\n /** Explicit field dependencies */\n dependsOn?: string[];\n\n /** Condition for when derivation applies */\n condition?: ConditionalExpression | boolean;\n}\n```\n\n## External Data in Derivations\n\nUse external application state in derivation expressions:\n\n```typescript\nconst config = {\n externalData: {\n discountRate: computed(() => pricingService.currentDiscount()),\n },\n fields: [\n {\n key: 'discountedPrice',\n type: 'input',\n label: 'Discounted Price',\n readonly: true,\n derivation: 'formValue.price * (1 - externalData.discountRate)',\n },\n ],\n} as const satisfies FormConfig;\n```\n\nExternal data values are reactively tracked - when signals change, derivations are re-evaluated.\n\n## Related\n\n- **Property Derivation** (see tab above) - Derive component properties (minDate, options, label) from form values\n- **[Conditional Logic](../conditional-logic/overview/)** - Control field visibility and state\n- **[Array Fields](../../prebuilt/form-arrays/)** - Working with array fields\n- **[Examples](/docs/examples)** - Real-world form patterns"
64
+ },
65
+ {
66
+ id: "dynamic-behavior-value-derivation-basics-property-derivation",
67
+ title: "Dynamic Behavior Value Derivation Basics Property Derivation",
68
+ category: "dynamic-behavior",
69
+ content: "Reactively derive field component properties (like `minDate`, `options`, `label`, `placeholder`) based on form values. While value derivations set a field's form value, property derivations set **component input properties**.\n\n## Quick Start\n\nProperty derivations use `type: 'propertyDerivation'` in the `logic` array and are self-targeting: the logic is placed on the field whose property should be derived.\n\n```typescript\n{\n key: 'endDate',\n type: 'datepicker',\n label: 'End Date',\n logic: [{\n type: 'propertyDerivation',\n targetProperty: 'minDate',\n expression: 'formValue.startDate',\n }]\n}\n```\n\nWhen `startDate` changes, the `minDate` property on `endDate`'s datepicker component is automatically updated.\n\n## Derivation Sources\n\nProperty derivations support three mutually exclusive ways to compute a value.\n\n### Expression-Based\n\nUse JavaScript expressions with access to `formValue`:\n\n```typescript\n{\n key: 'endDate',\n type: 'datepicker',\n label: 'End Date',\n logic: [{\n type: 'propertyDerivation',\n targetProperty: 'minDate',\n expression: 'formValue.startDate',\n }]\n}\n```\n\n**Available variables:**\n\n- `formValue` - Object containing all form field values\n- `externalData` - External application state (when configured in FormConfig)\n\n### Static Value\n\nSet a constant property value when a condition is met:\n\n```typescript\n{\n key: 'phone',\n type: 'input',\n label: 'Phone',\n logic: [{\n type: 'propertyDerivation',\n targetProperty: 'label',\n value: 'Mobile Phone',\n condition: {\n type: 'fieldValue',\n fieldPath: 'contactType',\n operator: 'equals',\n value: 'mobile',\n },\n }]\n}\n```\n\n### Custom Function\n\nUse a registered function for complex logic:\n\n```typescript\n// In form config\ncustomFnConfig: {\n propertyDerivations: {\n getCitiesForCountry: (ctx) => {\n const cities: Record<string, { label: string; value: string }[]> = {\n 'US': [{ label: 'New York', value: 'nyc' }, { label: 'LA', value: 'la' }],\n 'DE': [{ label: 'Berlin', value: 'berlin' }],\n };\n return cities[ctx.formValue.country as string] ?? [];\n },\n },\n},\nfields: [\n {\n key: 'city',\n type: 'select',\n label: 'City',\n options: [],\n logic: [{\n type: 'propertyDerivation',\n targetProperty: 'options',\n functionName: 'getCitiesForCountry',\n dependsOn: ['country'],\n }],\n },\n],\n```\n\n## Target Properties\n\n### Simple Properties\n\nSet any direct component input property:\n\n```typescript\ntargetProperty: 'minDate'; // Date constraint\ntargetProperty: 'maxDate'; // Date constraint\ntargetProperty: 'options'; // Select/radio options\ntargetProperty: 'label'; // Field label\ntargetProperty: 'placeholder'; // Input placeholder\ntargetProperty: 'hint'; // Hint text\ntargetProperty: 'rows'; // Textarea rows\n```\n\n### Nested Properties (Dot Notation)\n\nSet properties nested one level deep using dot notation:\n\n```typescript\ntargetProperty: 'props.appearance'; // Material appearance\ntargetProperty: 'props.color'; // Material color\ntargetProperty: 'meta.autocomplete'; // Custom metadata\n```\n\n> **Note:** Maximum nesting depth is 2 levels (one dot). Deeper paths like `props.nested.deep` are not supported.\n\n## Trigger Timing\n\nControl when property derivations evaluate:\n\n| Trigger | Description | Use Case |\n| ----------- | ------------------------------------- | --------------------------------- |\n| `onChange` | Immediately on value change (default) | Date constraints, dynamic options |\n| `debounced` | After value stabilizes | Expensive lookups, search queries |\n\n### Debounced Property Derivations\n\nUse `trigger: 'debounced'` for expensive operations:\n\n```typescript\n{\n key: 'productSearch',\n type: 'select',\n label: 'Product',\n options: [],\n logic: [{\n type: 'propertyDerivation',\n targetProperty: 'options',\n functionName: 'searchProducts',\n trigger: 'debounced',\n debounceMs: 300,\n dependsOn: ['searchQuery'],\n }]\n}\n```\n\n## Conditional Property Derivations\n\nOnly apply property derivations when conditions are met:\n\n```typescript\n{\n key: 'email',\n type: 'input',\n label: 'Email',\n logic: [\n {\n type: 'propertyDerivation',\n targetProperty: 'label',\n value: 'Work Email',\n condition: {\n type: 'fieldValue',\n fieldPath: 'accountType',\n operator: 'equals',\n value: 'business',\n },\n },\n {\n type: 'propertyDerivation',\n targetProperty: 'label',\n value: 'Personal Email',\n condition: {\n type: 'fieldValue',\n fieldPath: 'accountType',\n operator: 'equals',\n value: 'personal',\n },\n },\n ],\n}\n```\n\n## Dependencies\n\n### Automatic Detection\n\nFor expressions, dependencies are automatically extracted:\n\n```typescript\n{\n key: 'endDate',\n type: 'datepicker',\n label: 'End Date',\n logic: [{\n type: 'propertyDerivation',\n targetProperty: 'minDate',\n expression: 'formValue.startDate',\n // Automatically depends on: startDate\n }]\n}\n```\n\n### Explicit Dependencies\n\nFor custom functions, specify dependencies explicitly:\n\n```typescript\n{\n key: 'city',\n type: 'select',\n label: 'City',\n options: [],\n logic: [{\n type: 'propertyDerivation',\n targetProperty: 'options',\n functionName: 'getCitiesForCountry',\n dependsOn: ['country'],\n }]\n}\n```\n\nWithout `dependsOn`, custom functions re-evaluate on **any** form value change.\n\n## Array Field Property Derivations\n\nInside arrays, `formValue` is scoped to the current array item:\n\n```typescript\n{\n key: 'lineItems',\n type: 'array',\n fields: [\n {\n key: 'item',\n type: 'group',\n fields: [\n { key: 'startDate', type: 'datepicker', label: 'Start' },\n {\n key: 'endDate',\n type: 'datepicker',\n label: 'End',\n logic: [{\n type: 'propertyDerivation',\n targetProperty: 'minDate',\n // formValue is scoped to the current array item\n expression: 'formValue.startDate',\n }]\n },\n ],\n },\n ],\n}\n```\n\nEach array item independently derives its own `endDate.minDate` from its own `startDate`.\n\n## Complete Example\n\n```typescript\nconst travelForm = {\n customFnConfig: {\n propertyDerivations: {\n getCitiesForCountry: (ctx) => {\n const cities: Record<string, { label: string; value: string }[]> = {\n US: [\n { label: 'New York', value: 'nyc' },\n { label: 'Los Angeles', value: 'la' },\n { label: 'Chicago', value: 'chi' },\n ],\n DE: [\n { label: 'Berlin', value: 'berlin' },\n { label: 'Munich', value: 'munich' },\n ],\n };\n return cities[ctx.formValue.country as string] ?? [];\n },\n },\n },\n fields: [\n {\n key: 'country',\n type: 'select',\n label: 'Country',\n required: true,\n options: [\n { label: 'USA', value: 'US' },\n { label: 'Germany', value: 'DE' },\n ],\n },\n {\n key: 'city',\n type: 'select',\n label: 'City',\n required: true,\n options: [],\n logic: [\n {\n type: 'propertyDerivation',\n targetProperty: 'options',\n functionName: 'getCitiesForCountry',\n dependsOn: ['country'],\n },\n ],\n },\n { key: 'startDate', type: 'datepicker', label: 'Travel Start', required: true },\n {\n key: 'endDate',\n type: 'datepicker',\n label: 'Travel End',\n required: true,\n logic: [\n {\n type: 'propertyDerivation',\n targetProperty: 'minDate',\n expression: 'formValue.startDate',\n },\n ],\n },\n {\n key: 'notes',\n type: 'textarea',\n label: 'Notes',\n logic: [\n {\n type: 'propertyDerivation',\n targetProperty: 'props.appearance',\n value: 'fill',\n condition: {\n type: 'fieldValue',\n fieldPath: 'country',\n operator: 'equals',\n value: 'DE',\n },\n },\n {\n type: 'propertyDerivation',\n targetProperty: 'props.appearance',\n value: 'outline',\n condition: {\n type: 'fieldValue',\n fieldPath: 'country',\n operator: 'notEquals',\n value: 'DE',\n },\n },\n ],\n },\n { key: 'submit', type: 'submit', label: 'Book Trip' },\n ],\n} as const satisfies FormConfig;\n```\n\n## Comparison with Value Derivation\n\n| Aspect | Value Derivation | Property Derivation |\n| ---------------- | ---------------------------- | ------------------------------------ |\n| Logic type | `type: 'derivation'` | `type: 'propertyDerivation'` |\n| Sets | Field's form value | Component input property |\n| Target | Implicit (self) | `targetProperty: 'minDate'` |\n| Shorthand | `derivation: 'expr'` | None (must use logic block) |\n| Chaining | Topologically sorted | No chaining (single pass) |\n| Custom functions | `customFnConfig.derivations` | `customFnConfig.propertyDerivations` |\n| Max iterations | Configurable (default 10) | Single pass |\n\n## Debugging\n\nAdd `debugName` to property derivations for easier identification in logs:\n\n```typescript\nlogic: [\n {\n type: 'propertyDerivation',\n debugName: 'endDate minDate constraint',\n targetProperty: 'minDate',\n expression: 'formValue.startDate',\n },\n];\n```\n\n## PropertyDerivationLogicConfig Interface\n\n```typescript\ninterface PropertyDerivationLogicConfig {\n /** Logic type identifier */\n type: 'propertyDerivation';\n\n /** Property to set on the field component */\n targetProperty: string;\n\n /** Optional name for debugging */\n debugName?: string;\n\n /** When to evaluate: 'onChange' (default) or 'debounced' */\n trigger?: 'onChange' | 'debounced';\n\n /** Debounce duration in ms (default: 500) */\n debounceMs?: number;\n\n /** Static value to set (mutually exclusive) */\n value?: unknown;\n\n /** JavaScript expression (mutually exclusive) */\n expression?: string;\n\n /** Name of registered custom function (mutually exclusive) */\n functionName?: string;\n\n /** Explicit field dependencies */\n dependsOn?: string[];\n\n /** Condition for when derivation applies (default: true) */\n condition?: ConditionalExpression | boolean;\n}\n```\n\n## External Data in Property Derivations\n\nUse external application state in property derivation custom functions:\n\n```typescript\nconst config = {\n externalData: {\n userRegion: computed(() => this.regionService.current()),\n },\n customFnConfig: {\n propertyDerivations: {\n getCurrencyOptions: (ctx) => {\n const optionsByRegion: Record<string, { label: string; value: string }[]> = {\n EU: [\n { label: 'EUR', value: 'eur' },\n { label: 'GBP', value: 'gbp' },\n ],\n US: [\n { label: 'USD', value: 'usd' },\n { label: 'CAD', value: 'cad' },\n ],\n };\n return optionsByRegion[ctx.externalData.userRegion as string] ?? [];\n },\n },\n },\n fields: [\n {\n key: 'currency',\n type: 'select',\n label: 'Currency',\n options: [],\n logic: [\n {\n type: 'propertyDerivation',\n targetProperty: 'options',\n functionName: 'getCurrencyOptions',\n },\n ],\n },\n ],\n} as const satisfies FormConfig;\n```\n\nExternal data values are reactively tracked - when signals change, property derivations are re-evaluated.\n\n## Related\n\n- **Value Derivation** (see tab above) - Compute field form values\n- **[Conditional Logic](../conditional-logic/overview/)** - Control field visibility and state\n- **[Array Fields](../../prebuilt/form-arrays/)** - Working with array fields"
64
70
  },
65
71
  {
66
72
  id: "age-conditional-form",
@@ -132,13 +138,13 @@ var require_docs = __commonJS({
132
138
  id: "form-arrays",
133
139
  title: "Form Arrays",
134
140
  category: "prebuilt",
135
- content: "Arrays create dynamic collections of field values. The fields array defines a **template** that is cloned for each array item.\n\n## Interactive Demo\n\n<iframe src=\"http://localhost:4201/#/examples/array-field\" class=\"example-frame\" title=\"Array Field Demo\"></iframe>\n\n## Flat Arrays (Primitive Values)\n\nFor simple arrays of primitive values, use a leaf field as the template:\n\n```typescript\n{\n key: 'tags',\n type: 'array',\n fields: [\n { key: 'tag', type: 'input', label: 'Tag', value: '' }\n ],\n}\n```\n\nThis creates a flat array in the form value:\n\n```typescript\n{\n tags: ['tag1', 'tag2', 'tag3'];\n}\n```\n\n## Object Arrays (Nested Groups)\n\nFor arrays of objects, use a group field as the template:\n\n```typescript\n{\n key: 'contacts',\n type: 'array',\n fields: [{\n type: 'group',\n fields: [\n { key: 'name', type: 'input', label: 'Name', value: '' },\n { key: 'phone', type: 'input', label: 'Phone', value: '' }\n ]\n }],\n}\n```\n\nThis creates an array of objects:\n\n```typescript\n{\n contacts: [\n { name: 'John Doe', phone: '5551234567' },\n { name: 'Jane Smith', phone: '5559876543' },\n ];\n}\n```\n\n## Array vs Group\n\n- **Groups** create nested objects with keys: `{ address: { street: '', city: '' } }`\n- **Flat Arrays** create lists of values: `{ tags: ['value1', 'value2'] }`\n- **Object Arrays** create lists of objects: `{ items: [{name: ''}, {name: ''}] }`\n\n## Dynamic Add/Remove\n\nArray items can be added or removed dynamically at runtime using the event bus:\n\n```typescript\nimport { EventBus, AddArrayItemEvent, RemoveArrayItemEvent } from '@ng-forge/dynamic-forms';\n\n// Inject the event bus\neventBus = inject(EventBus);\n\n// Add item to array\naddItem() {\n this.eventBus.dispatch(AddArrayItemEvent, 'tags');\n}\n\n// Add item at specific index\naddItemAt(index: number) {\n this.eventBus.dispatch(AddArrayItemEvent, 'tags', index);\n}\n\n// Remove last item\nremoveItem() {\n this.eventBus.dispatch(RemoveArrayItemEvent, 'tags');\n}\n\n// Remove item at specific index\nremoveItemAt(index: number) {\n this.eventBus.dispatch(RemoveArrayItemEvent, 'tags', index);\n}\n```\n\n## Use Cases\n\nArrays are ideal for:\n\n- Lists of simple values (tags, categories, keywords)\n- Repeating form sections (multiple addresses, phone numbers)\n- Dynamic collections where items can be added/removed\n- Collection-based data structures where order matters\n\n## Complete Example: Flat Array\n\nHere's a complete working example of a flat array field with dynamic add/remove:\n\n```typescript\nimport { Component, inject } from '@angular/core';\nimport { DynamicForm, EventBus, AddArrayItemEvent, RemoveArrayItemEvent } from '@ng-forge/dynamic-forms';\n\n@Component({\n selector: 'app-tags-form',\n imports: [DynamicForm],\n template: `\n <form [dynamic-form]=\"formConfig\"></form>\n <button (click)=\"addTag()\">Add Tag</button>\n `,\n})\nexport class TagsFormComponent {\n private eventBus = inject(EventBus);\n\n formConfig = {\n fields: [\n // Note: Array fields don't support the 'label' property.\n // Use a text field above if you need a section header.\n {\n key: 'tags',\n type: 'array',\n fields: [\n {\n key: 'tag',\n type: 'input',\n label: 'Tag',\n value: '',\n required: true,\n minLength: 2,\n },\n ],\n },\n ],\n };\n\n addTag() {\n this.eventBus.dispatch(AddArrayItemEvent, 'tags');\n }\n\n removeTag(index: number) {\n this.eventBus.dispatch(RemoveArrayItemEvent, 'tags', index);\n }\n}\n```\n\n## Complete Example: Object Array\n\nHere's a complete working example of an object array field with validation:\n\n```typescript\nimport { Component, inject } from '@angular/core';\nimport { DynamicForm, EventBus, AddArrayItemEvent, RemoveArrayItemEvent } from '@ng-forge/dynamic-forms';\n\n@Component({\n selector: 'app-contacts-form',\n imports: [DynamicForm],\n template: `\n <form [dynamic-form]=\"formConfig\"></form>\n <button (click)=\"addContact()\">Add Contact</button>\n `,\n})\nexport class ContactsFormComponent {\n private eventBus = inject(EventBus);\n\n formConfig = {\n fields: [\n // Note: Array fields don't support the 'label' property.\n // Use a text field above if you need a section header.\n {\n key: 'contacts',\n type: 'array',\n fields: [\n {\n type: 'group',\n fields: [\n {\n key: 'name',\n type: 'input',\n label: 'Contact Name',\n value: '',\n required: true,\n minLength: 2,\n },\n {\n key: 'phone',\n type: 'input',\n label: 'Phone Number',\n value: '',\n required: true,\n pattern: /^\\d{10}$/,\n },\n {\n key: 'relationship',\n type: 'select',\n label: 'Relationship',\n value: 'friend',\n options: [\n { label: 'Family', value: 'family' },\n { label: 'Friend', value: 'friend' },\n { label: 'Colleague', value: 'colleague' },\n ],\n },\n ],\n },\n ],\n },\n ],\n };\n\n addContact() {\n this.eventBus.dispatch(AddArrayItemEvent, 'contacts');\n }\n\n removeContact(index: number) {\n this.eventBus.dispatch(RemoveArrayItemEvent, 'contacts', index);\n }\n}\n```\n\n## Template Field Concept\n\nThe key concept is that the `fields` array contains a **template** (typically one field definition):\n\n- **Flat arrays**: Template is a leaf field \u2192 creates `[value1, value2]`\n- **Object arrays**: Template is a group field \u2192 creates `[{...}, {...}]`\n\nWhen you add an array item via the event bus, the template is cloned and a new instance is created with the appropriate default value.\n\n## Nesting Constraints\n\nArray fields can be used within:\n\n- Pages (top-level container)\n- Rows (for horizontal layouts)\n- Groups (for nested arrays within objects)\n\nArrays **cannot** contain:\n\n- Other array fields (no nested arrays)\n- Page fields\n\n## Allowed Children (as template)\n\nArrays can use these field types as templates:\n\n- Leaf fields (input, select, checkbox, etc.) \u2192 creates flat arrays\n- Group fields \u2192 creates object arrays\n- Row fields \u2192 for horizontal layouts within each array item\n\nSee [Type Safety & Inference](../advanced/type-safety/basics) for details on how arrays affect type inference."
141
+ content: "Arrays create dynamic collections of field values. Each item in the `fields` array defines **one array item** with its structure and initial values.\n\n## Interactive Demo\n\n<iframe src=\"http://localhost:4201/#/examples/array\" class=\"example-frame\" title=\"Array Field Demo\"></iframe>\n\n## Structure Overview\n\nThe `fields` property supports two item formats:\n\n- **Single FieldDef** (not wrapped in array) \u2192 **Primitive item** - extracts field value directly\n- **Array of FieldDefs** \u2192 **Object item** - merges fields into an object\n\n```typescript\n// Primitive array: ['angular', 'typescript']\n{\n key: 'tags',\n type: 'array',\n fields: [\n { key: 'tag', type: 'input', value: 'angular' }, // Single field = primitive\n { key: 'tag', type: 'input', value: 'typescript' },\n ]\n}\n\n// Object array: [{ name: 'Alice', email: '...' }]\n{\n key: 'contacts',\n type: 'array',\n fields: [\n [ // Array of fields = object\n { key: 'name', type: 'input', label: 'Name', value: 'Alice' },\n { key: 'email', type: 'input', label: 'Email', value: 'alice@example.com' }\n ],\n ]\n}\n```\n\n## Empty Arrays (No Initial Items)\n\nFor arrays that start empty and are populated via buttons:\n\n```typescript\n{\n key: 'tags',\n type: 'array',\n fields: [] // No initial items - user adds via button\n}\n```\n\n## Initial Values\n\nInitial values are defined directly on each field via the `value` property - no separate `initialValue` is needed:\n\n```typescript\n{\n key: 'emails',\n type: 'array',\n fields: [\n // One initial item with pre-filled value (object item)\n [\n { key: 'email', type: 'input', label: 'Email', value: 'primary@example.com' }\n ]\n ]\n}\n```\n\n## Primitive Arrays (Simple Value Lists)\n\nFor simple arrays of primitive values like `['tag1', 'tag2']`, use a **single FieldDef per item** (not wrapped in an array):\n\n```typescript\n{\n key: 'tags',\n type: 'array',\n fields: [\n { key: 'tag', type: 'input', label: 'Tag', value: 'featured' },\n { key: 'tag', type: 'input', label: 'Tag', value: 'popular' }\n ]\n}\n```\n\nThis creates a true primitive array in the form value:\n\n```typescript\n{\n tags: ['featured', 'popular'];\n}\n```\n\nThe `key` property on each field is used for internal tracking but doesn't affect the output value.\n\n## Object Arrays (Multiple Fields per Item)\n\nFor arrays of objects with multiple fields, wrap the fields in an **inner array**:\n\n```typescript\n{\n key: 'contacts',\n type: 'array',\n fields: [\n [\n { key: 'name', type: 'input', label: 'Name', value: '' },\n { key: 'phone', type: 'input', label: 'Phone', value: '' }\n ]\n ]\n}\n```\n\nThis creates an array of objects:\n\n```typescript\n{\n contacts: [{ name: '', phone: '' }];\n}\n```\n\n## Nested Object Arrays (Using Groups)\n\nFor arrays with nested object structure, use a group field:\n\n```typescript\n{\n key: 'contacts',\n type: 'array',\n fields: [\n [\n {\n key: 'contact',\n type: 'group',\n fields: [\n { key: 'name', type: 'input', label: 'Name', value: '' },\n { key: 'phone', type: 'input', label: 'Phone', value: '' }\n ]\n }\n ]\n ]\n}\n```\n\nThis creates an array of nested objects (note the group key creates the nesting):\n\n```typescript\n{\n contacts: [{ contact: { name: '', phone: '' } }];\n}\n```\n\n## Heterogeneous Arrays (Mixed Primitives and Objects)\n\nArrays can contain both primitive and object items in the same array:\n\n```typescript\n{\n key: 'items',\n type: 'array',\n fields: [\n [{ key: 'label', type: 'input', value: 'Structured' }], // Object item (wrapped in array)\n { key: 'value', type: 'input', value: 'Simple' }, // Primitive item (single field)\n ]\n}\n```\n\nThis creates a heterogeneous array:\n\n```typescript\n{\n items: [{ label: 'Structured' }, 'Simple'];\n}\n```\n\n## Array vs Group\n\n- **Groups** create nested objects with keys: `{ address: { street: '', city: '' } }`\n- **Primitive Arrays** create lists of values: `{ tags: ['value1', 'value2'] }`\n- **Object Arrays** create lists of objects: `{ items: [{name: ''}, {name: ''}] }`\n\n## Dynamic Add/Remove\n\n### Declarative Approach (Recommended)\n\nUse button field types directly in your form configuration for declarative array manipulation:\n\n| Button Type | Placement | Description |\n| ------------------ | ---------------- | ------------------------------------------------ |\n| `addArrayItem` | Outside array | Appends a new item to the end of the array |\n| `prependArrayItem` | Outside array | Inserts a new item at the beginning of the array |\n| `insertArrayItem` | Outside array | Inserts a new item at a specific index |\n| `removeArrayItem` | Inside each item | Removes the current item from the array |\n| `popArrayItem` | Outside array | Removes the last item from the array |\n| `shiftArrayItem` | Outside array | Removes the first item from the array |\n\n**Important:** Add/prepend/insert buttons **require** a `template` property defining the new item structure. There is no fallback to the array's `fields[0]` - each button must explicitly define what structure to add.\n\nThe `template` can be:\n\n- **Single FieldDef** - creates a primitive item (field value is extracted directly)\n- **Array of FieldDefs** - creates an object item (fields merged into object)\n\n```typescript\n// Template for PRIMITIVE items (single field, not wrapped)\nconst tagTemplate = { key: 'tag', type: 'input', label: 'Tag' };\n\n// Template for OBJECT items (array of fields)\nconst contactTemplate = [\n { key: 'name', type: 'input', label: 'Name' },\n { key: 'phone', type: 'input', label: 'Phone' },\n // Remove button inside each item (no template needed)\n { key: 'remove', type: 'removeArrayItem', label: 'Remove' },\n];\n\n// Form configuration\n{\n fields: [\n {\n key: 'tags',\n type: 'array',\n fields: [], // Start empty - primitive array\n },\n // Add button for primitive items\n {\n key: 'addTag',\n type: 'addArrayItem',\n label: 'Add Tag',\n arrayKey: 'tags',\n template: tagTemplate, // Single field = primitive item\n },\n {\n key: 'contacts',\n type: 'array',\n fields: [], // Start empty - object array\n },\n // Add button for object items\n {\n key: 'addContact',\n type: 'addArrayItem',\n label: 'Add Contact',\n arrayKey: 'contacts',\n template: contactTemplate, // Array of fields = object item\n },\n ];\n}\n```\n\n### Programmatic Approach\n\nFor more control, use the event bus with the `arrayEvent` builder. **Note:** When using the programmatic approach, you must provide a template:\n\n```typescript\nimport { EventBus, arrayEvent } from '@ng-forge/dynamic-forms';\n\n// Inject the event bus\neventBus = inject(EventBus);\n\n// Template for PRIMITIVE items (single field, not wrapped)\ntagTemplate = { key: 'tag', type: 'input', label: 'Tag', value: '' };\n\n// Template for OBJECT items (array of fields)\ncontactTemplate = [\n { key: 'name', type: 'input', label: 'Name', value: '' },\n { key: 'phone', type: 'input', label: 'Phone', value: '' }\n];\n\n// Add PRIMITIVE item to end of array\naddTag() {\n this.eventBus.dispatch(arrayEvent('tags').append(this.tagTemplate));\n}\n\n// Add OBJECT item to end of array\naddContact() {\n this.eventBus.dispatch(arrayEvent('contacts').append(this.contactTemplate));\n}\n\n// Add item to beginning of array\nprependItem() {\n this.eventBus.dispatch(arrayEvent('contacts').prepend(this.contactTemplate));\n}\n\n// Add item at specific index\naddItemAt(index: number) {\n this.eventBus.dispatch(arrayEvent('contacts').insertAt(index, this.contactTemplate));\n}\n\n// Remove last item (no template needed)\nremoveLastItem() {\n this.eventBus.dispatch(arrayEvent('contacts').pop());\n}\n\n// Remove first item (no template needed)\nremoveFirstItem() {\n this.eventBus.dispatch(arrayEvent('contacts').shift());\n}\n\n// Remove item at specific index (no template needed)\nremoveItemAt(index: number) {\n this.eventBus.dispatch(arrayEvent('contacts').removeAt(index));\n}\n```\n\n## Use Cases\n\nArrays are ideal for:\n\n- Lists of simple values (tags, categories, keywords)\n- Repeating form sections (multiple addresses, phone numbers)\n- Dynamic collections where items can be added/removed\n- Collection-based data structures where order matters\n\n## Complete Example: Primitive Array with Initial Values\n\nHere's a complete working example of a primitive array field (simple value list) with initial values and dynamic add/remove:\n\n```typescript\nimport { Component, inject } from '@angular/core';\nimport { DynamicForm, EventBus, arrayEvent } from '@ng-forge/dynamic-forms';\n\n@Component({\n selector: 'app-tags-form',\n imports: [DynamicForm],\n template: `\n <form [dynamic-form]=\"formConfig\"></form>\n <button (click)=\"addTag()\">Add Tag</button>\n `,\n})\nexport class TagsFormComponent {\n private eventBus = inject(EventBus);\n\n // Template for new tags - single field (primitive item)\n private tagTemplate = {\n key: 'tag',\n type: 'input',\n label: 'Tag',\n value: '',\n required: true,\n minLength: 2,\n };\n\n formConfig = {\n fields: [\n {\n key: 'tags',\n type: 'array',\n // Start with two initial tags (primitive items - not wrapped in arrays)\n fields: [\n { key: 'tag', type: 'input', label: 'Tag', value: 'featured', required: true, minLength: 2 },\n { key: 'tag', type: 'input', label: 'Tag', value: 'popular', required: true, minLength: 2 },\n ],\n },\n ],\n };\n\n // Form value: { tags: ['featured', 'popular'] }\n\n addTag() {\n this.eventBus.dispatch(arrayEvent('tags').append(this.tagTemplate));\n }\n\n removeTag(index: number) {\n this.eventBus.dispatch(arrayEvent('tags').removeAt(index));\n }\n}\n```\n\n## Complete Example: Object Array with Initial Values\n\nHere's a complete working example of an object array field with initial values and validation:\n\n```typescript\nimport { Component, inject } from '@angular/core';\nimport { DynamicForm, EventBus, arrayEvent } from '@ng-forge/dynamic-forms';\n\n@Component({\n selector: 'app-contacts-form',\n imports: [DynamicForm],\n template: `\n <form [dynamic-form]=\"formConfig\"></form>\n <button (click)=\"addContact()\">Add Contact</button>\n `,\n})\nexport class ContactsFormComponent {\n private eventBus = inject(EventBus);\n\n // Template for new contacts\n private contactTemplate = [\n { key: 'name', type: 'input', label: 'Contact Name', value: '', required: true, minLength: 2 },\n { key: 'phone', type: 'input', label: 'Phone Number', value: '', required: true, pattern: /^\\d{10}$/ },\n {\n key: 'relationship',\n type: 'select',\n label: 'Relationship',\n value: 'friend',\n options: [\n { label: 'Family', value: 'family' },\n { label: 'Friend', value: 'friend' },\n { label: 'Colleague', value: 'colleague' },\n ],\n },\n ];\n\n formConfig = {\n fields: [\n {\n key: 'contacts',\n type: 'array',\n // Start with one pre-filled contact\n fields: [\n [\n { key: 'name', type: 'input', label: 'Contact Name', value: 'John Doe', required: true, minLength: 2 },\n { key: 'phone', type: 'input', label: 'Phone Number', value: '5551234567', required: true, pattern: /^\\d{10}$/ },\n {\n key: 'relationship',\n type: 'select',\n label: 'Relationship',\n value: 'family',\n options: [\n { label: 'Family', value: 'family' },\n { label: 'Friend', value: 'friend' },\n { label: 'Colleague', value: 'colleague' },\n ],\n },\n ],\n ],\n },\n ],\n };\n\n // Form value: { contacts: [{ name: 'John Doe', phone: '5551234567', relationship: 'family' }] }\n\n addContact() {\n this.eventBus.dispatch(arrayEvent('contacts').append(this.contactTemplate));\n }\n\n removeContact(index: number) {\n this.eventBus.dispatch(arrayEvent('contacts').removeAt(index));\n }\n}\n```\n\n## Template Requirement\n\n**Important:** When adding items dynamically (via buttons or event bus), you must always provide an explicit `template`. There is no automatic fallback to use the first item's structure.\n\nThis design ensures:\n\n- Clear intent - each add operation explicitly defines what to add\n- Flexibility - different buttons can add different item structures\n- No ambiguity - the array's `fields` only defines initial items, not a \"default template\"\n\n## Heterogeneous Items\n\nArrays can have items with different field structures:\n\n```typescript\n{\n key: 'entries',\n type: 'array',\n fields: [\n // Item 0: Simple tag\n [{ key: 'tag', type: 'input', label: 'Tag', value: 'simple' }],\n // Item 1: Contact with more fields\n [\n { key: 'name', type: 'input', label: 'Name', value: 'Alice' },\n { key: 'email', type: 'input', label: 'Email', value: 'alice@example.com' }\n ]\n ]\n}\n```\n\nThis flexibility allows each item to have its own structure, though typically all items share the same structure for consistency.\n\n## Nesting Constraints\n\nArray fields can be used within:\n\n- Pages (top-level container)\n- Rows (for horizontal layouts)\n- Groups (for nested arrays within objects)\n\nArrays **cannot** contain:\n\n- Other array fields (no nested arrays)\n- Page fields\n\n## Allowed Children\n\nArrays can contain these field types:\n\n- Leaf fields (input, select, checkbox, etc.) -> creates flat or object arrays\n- Group fields with key -> creates nested object arrays `[{groupKey: {...}}, ...]`\n- Row fields -> creates flat object arrays `[{...}, {...}]` (rows don't add nesting)\n- Button fields (for remove operations inside each item)\n\nSee [Type Safety & Inference](../advanced/type-safety/basics) for details on how arrays affect type inference."
136
142
  },
137
143
  {
138
144
  id: "form-groups",
139
145
  title: "Form Groups",
140
146
  category: "prebuilt",
141
- content: "Groups nest form fields under a single key in the form value. This creates logical grouping for form data, not visual grouping.\n\n## Interactive Demo\n\n<iframe src=\"http://localhost:4201/#/examples/group-field\" class=\"example-frame\" title=\"Group Field Demo\"></iframe>\n\n## Basic Group\n\n```typescript\n{\n type: 'group',\n key: 'address',\n fields: [\n { key: 'street', type: 'input', label: 'Street', value: '' },\n { key: 'city', type: 'input', label: 'City', value: '' },\n { key: 'zip', type: 'input', label: 'ZIP', value: '' },\n ],\n}\n```\n\nThis creates a nested structure in the form value:\n\n```typescript\n{\n address: {\n street: '',\n city: '',\n zip: ''\n }\n}\n```\n\nGroups are for organizing form **data**, not UI. The visual presentation depends on your UI integration (Material, Bootstrap, etc.).\n\n## Complete Example\n\nHere's a complete working example of a group field with validation:\n\n```typescript\nimport { Component } from '@angular/core';\nimport { DynamicForm } from '@ng-forge/dynamic-forms';\n\n@Component({\n selector: 'app-user-profile-form',\n imports: [DynamicForm],\n template: `<form [dynamic-form]=\"formConfig\"></form>`,\n})\nexport class UserProfileFormComponent {\n formConfig = {\n fields: [\n {\n key: 'name',\n type: 'input',\n label: 'Full Name',\n value: '',\n required: true,\n },\n {\n key: 'address',\n type: 'group',\n fields: [\n {\n key: 'street',\n type: 'input',\n label: 'Street Address',\n value: '',\n required: true,\n },\n {\n key: 'city',\n type: 'input',\n label: 'City',\n value: '',\n required: true,\n },\n {\n key: 'state',\n type: 'input',\n label: 'State',\n value: '',\n required: true,\n maxLength: 2,\n },\n {\n key: 'zip',\n type: 'input',\n label: 'ZIP Code',\n value: '',\n required: true,\n pattern: /^\\d{5}$/,\n },\n ],\n },\n ],\n };\n}\n```\n\nThis produces a form value with nested structure:\n\n```typescript\n{\n name: 'John Doe',\n address: {\n street: '123 Main St',\n city: 'Springfield',\n state: 'IL',\n zip: '62701'\n }\n}\n```\n\n## Nesting Restrictions\n\nGroup fields can be used within:\n\n- Pages (top-level container)\n- Rows (for horizontal layouts)\n- Array fields (for creating object arrays where each array item is an object)\n\nGroups **cannot** be nested inside:\n\n- Other group fields (no nested groups)\n\n## Allowed Children\n\nGroups can contain:\n\n- Leaf fields (input, select, checkbox, etc.)\n- Row fields (for horizontal layouts within the group)\n\nSee [Type Safety & Inference](../advanced/type-safety/basics) for details on how groups affect type inference."
147
+ content: "Groups nest form fields under a single key in the form value. This creates logical grouping for form data, not visual grouping.\n\n## Interactive Demo\n\n<iframe src=\"http://localhost:4201/#/examples/group\" class=\"example-frame\" title=\"Group Field Demo\"></iframe>\n\n## Basic Group\n\n```typescript\n{\n type: 'group',\n key: 'address',\n fields: [\n { key: 'street', type: 'input', label: 'Street', value: '' },\n { key: 'city', type: 'input', label: 'City', value: '' },\n { key: 'zip', type: 'input', label: 'ZIP', value: '' },\n ],\n}\n```\n\nThis creates a nested structure in the form value:\n\n```typescript\n{\n address: {\n street: '',\n city: '',\n zip: ''\n }\n}\n```\n\nGroups are for organizing form **data**, not UI. The visual presentation depends on your UI integration (Material, Bootstrap, etc.).\n\n## Complete Example\n\nHere's a complete working example of a group field with validation:\n\n```typescript\nimport { Component } from '@angular/core';\nimport { DynamicForm } from '@ng-forge/dynamic-forms';\n\n@Component({\n selector: 'app-user-profile-form',\n imports: [DynamicForm],\n template: `<form [dynamic-form]=\"formConfig\"></form>`,\n})\nexport class UserProfileFormComponent {\n formConfig = {\n fields: [\n {\n key: 'name',\n type: 'input',\n label: 'Full Name',\n value: '',\n required: true,\n },\n {\n key: 'address',\n type: 'group',\n fields: [\n {\n key: 'street',\n type: 'input',\n label: 'Street Address',\n value: '',\n required: true,\n },\n {\n key: 'city',\n type: 'input',\n label: 'City',\n value: '',\n required: true,\n },\n {\n key: 'state',\n type: 'input',\n label: 'State',\n value: '',\n required: true,\n maxLength: 2,\n },\n {\n key: 'zip',\n type: 'input',\n label: 'ZIP Code',\n value: '',\n required: true,\n pattern: /^\\d{5}$/,\n },\n ],\n },\n ],\n };\n}\n```\n\nThis produces a form value with nested structure:\n\n```typescript\n{\n name: 'John Doe',\n address: {\n street: '123 Main St',\n city: 'Springfield',\n state: 'IL',\n zip: '62701'\n }\n}\n```\n\n## Nesting Restrictions\n\nGroup fields can be used within:\n\n- Pages (top-level container)\n- Rows (for horizontal layouts)\n- Array fields (for creating object arrays where each array item is an object)\n\nGroups **cannot** be nested inside:\n\n- Other group fields (no nested groups)\n\n## Allowed Children\n\nGroups can contain:\n\n- Leaf fields (input, select, checkbox, etc.)\n- Row fields (for horizontal layouts within the group)\n\nSee [Type Safety & Inference](../advanced/type-safety/basics) for details on how groups affect type inference."
142
148
  },
143
149
  {
144
150
  id: "form-pages",
@@ -150,7 +156,7 @@ var require_docs = __commonJS({
150
156
  id: "form-rows",
151
157
  title: "Form Rows",
152
158
  category: "prebuilt",
153
- content: "Organize fields into horizontal rows for compact layouts. Rows display fields side-by-side.\n\n## Interactive Demo\n\n<iframe src=\"http://localhost:4201/#/examples/row-field\" class=\"example-frame\" title=\"Row Field Demo\"></iframe>\n\n## Basic Row\n\n```typescript\n{\n type: 'row',\n fields: [\n { key: 'firstName', type: 'input', label: 'First Name', value: '', col: 6 },\n { key: 'lastName', type: 'input', label: 'Last Name', value: '', col: 6 },\n ],\n}\n```\n\nRows flatten their children - they don't add nesting to form values. Use the `col` property to control field widths (see Column Sizing below).\n\n## Column Sizing\n\nControl field widths within rows using the `col` property:\n\n```typescript\n{\n type: 'row',\n fields: [\n { key: 'city', type: 'input', label: 'City', value: '', col: 6 },\n { key: 'state', type: 'select', label: 'State', value: '', col: 3 },\n { key: 'zip', type: 'input', label: 'ZIP', value: '', col: 3 },\n ],\n}\n```\n\nThe `col` property uses a 12-column grid system (like Bootstrap). In this example:\n\n- `city` takes 6/12 (50%) width\n- `state` takes 3/12 (25%) width\n- `zip` takes 3/12 (25%) width\n\n## Responsive Behavior\n\nRows automatically stack on small screens, making forms mobile-friendly without additional configuration.\n\n## Complete Example\n\nHere's a complete working example of a row field with multiple fields:\n\n```typescript\nimport { Component } from '@angular/core';\nimport { DynamicForm } from '@ng-forge/dynamic-forms';\n\n@Component({\n selector: 'app-address-form',\n imports: [DynamicForm],\n template: `<form [dynamic-form]=\"formConfig\"></form>\n >`,\n})\nexport class AddressFormComponent {\n formConfig = {\n fields: [\n {\n type: 'row',\n fields: [\n {\n key: 'firstName',\n type: 'input',\n label: 'First Name',\n value: '',\n required: true,\n col: 6,\n },\n {\n key: 'lastName',\n type: 'input',\n label: 'Last Name',\n value: '',\n required: true,\n col: 6,\n },\n ],\n },\n {\n key: 'email',\n type: 'input',\n label: 'Email Address',\n value: '',\n required: true,\n email: true,\n },\n {\n type: 'row',\n fields: [\n {\n key: 'city',\n type: 'input',\n label: 'City',\n value: '',\n required: true,\n col: 6,\n },\n {\n key: 'state',\n type: 'input',\n label: 'State',\n value: '',\n required: true,\n maxLength: 2,\n col: 3,\n },\n {\n key: 'zip',\n type: 'input',\n label: 'ZIP',\n value: '',\n required: true,\n pattern: /^\\d{5}$/,\n col: 3,\n },\n ],\n },\n ],\n };\n}\n```\n\nThis produces a flat form value (rows don't create nesting):\n\n```typescript\n{\n firstName: 'John',\n lastName: 'Doe',\n email: 'john.doe@example.com',\n city: 'Springfield',\n state: 'IL',\n zip: '62701'\n}\n```\n\n## Value Structure\n\nRows are layout containers - they don't add nesting to your form values. Fields flatten to the root level:\n\n```typescript\n// Form config with rows\n{\n fields: [\n {\n type: 'row',\n fields: [\n { key: 'firstName', type: 'input', value: '', col: 6 },\n { key: 'lastName', type: 'input', value: '', col: 6 },\n ],\n },\n ];\n}\n\n// Resulting form value (flat structure)\n{\n firstName: 'John',\n lastName: 'Doe',\n // Note: row itself is NOT in the value\n}\n```\n\n## Nesting Restrictions\n\nRow fields can be used within:\n\n- Pages (top-level container)\n- Groups (for layouts within grouped data)\n- Arrays (for layouts within array items)\n\nRows **cannot** be nested inside:\n\n- Other row fields\n\n## Allowed Children\n\nRows can contain:\n\n- Leaf fields (input, select, checkbox, etc.)\n- Group fields (for nested data structures within the row)\n- Array fields (for repeating sections within the row)"
159
+ content: "Organize fields into horizontal rows for compact layouts. Rows display fields side-by-side.\n\n## Interactive Demo\n\n<iframe src=\"http://localhost:4201/#/examples/row\" class=\"example-frame\" title=\"Row Field Demo\"></iframe>\n\n## Basic Row\n\n```typescript\n{\n type: 'row',\n fields: [\n { key: 'firstName', type: 'input', label: 'First Name', value: '', col: 6 },\n { key: 'lastName', type: 'input', label: 'Last Name', value: '', col: 6 },\n ],\n}\n```\n\nRows flatten their children - they don't add nesting to form values. Use the `col` property to control field widths (see Column Sizing below).\n\n## Column Sizing\n\nControl field widths within rows using the `col` property:\n\n```typescript\n{\n type: 'row',\n fields: [\n { key: 'city', type: 'input', label: 'City', value: '', col: 6 },\n { key: 'state', type: 'select', label: 'State', value: '', col: 3 },\n { key: 'zip', type: 'input', label: 'ZIP', value: '', col: 3 },\n ],\n}\n```\n\nThe `col` property uses a 12-column grid system (like Bootstrap). In this example:\n\n- `city` takes 6/12 (50%) width\n- `state` takes 3/12 (25%) width\n- `zip` takes 3/12 (25%) width\n\n## Responsive Behavior\n\nRows automatically stack on small screens, making forms mobile-friendly without additional configuration.\n\n## Complete Example\n\nHere's a complete working example of a row field with multiple fields:\n\n```typescript\nimport { Component } from '@angular/core';\nimport { DynamicForm } from '@ng-forge/dynamic-forms';\n\n@Component({\n selector: 'app-address-form',\n imports: [DynamicForm],\n template: `<form [dynamic-form]=\"formConfig\"></form>\n >`,\n})\nexport class AddressFormComponent {\n formConfig = {\n fields: [\n {\n type: 'row',\n fields: [\n {\n key: 'firstName',\n type: 'input',\n label: 'First Name',\n value: '',\n required: true,\n col: 6,\n },\n {\n key: 'lastName',\n type: 'input',\n label: 'Last Name',\n value: '',\n required: true,\n col: 6,\n },\n ],\n },\n {\n key: 'email',\n type: 'input',\n label: 'Email Address',\n value: '',\n required: true,\n email: true,\n },\n {\n type: 'row',\n fields: [\n {\n key: 'city',\n type: 'input',\n label: 'City',\n value: '',\n required: true,\n col: 6,\n },\n {\n key: 'state',\n type: 'input',\n label: 'State',\n value: '',\n required: true,\n maxLength: 2,\n col: 3,\n },\n {\n key: 'zip',\n type: 'input',\n label: 'ZIP',\n value: '',\n required: true,\n pattern: /^\\d{5}$/,\n col: 3,\n },\n ],\n },\n ],\n };\n}\n```\n\nThis produces a flat form value (rows don't create nesting):\n\n```typescript\n{\n firstName: 'John',\n lastName: 'Doe',\n email: 'john.doe@example.com',\n city: 'Springfield',\n state: 'IL',\n zip: '62701'\n}\n```\n\n## Value Structure\n\nRows are layout containers - they don't add nesting to your form values. Fields flatten to the root level:\n\n```typescript\n// Form config with rows\n{\n fields: [\n {\n type: 'row',\n fields: [\n { key: 'firstName', type: 'input', value: '', col: 6 },\n { key: 'lastName', type: 'input', value: '', col: 6 },\n ],\n },\n ];\n}\n\n// Resulting form value (flat structure)\n{\n firstName: 'John',\n lastName: 'Doe',\n // Note: row itself is NOT in the value\n}\n```\n\n## Nesting Restrictions\n\nRow fields can be used within:\n\n- Pages (top-level container)\n- Groups (for layouts within grouped data)\n- Arrays (for layouts within array items)\n\nRows **cannot** be nested inside:\n\n- Other row fields\n\n## Allowed Children\n\nRows can contain:\n\n- Leaf fields (input, select, checkbox, etc.)\n- Group fields (for nested data structures within the row)\n- Array fields (for repeating sections within the row)"
154
160
  },
155
161
  {
156
162
  id: "hidden-fields",
@@ -5958,7 +5964,8 @@ See topic \`external-data\` for full documentation.`
5958
5964
  logic: [{ type: 'derivation', expression: 'formValue.firstName + " " + formValue.lastName' }]
5959
5965
  \`\`\`
5960
5966
  Derivation is always defined ON the field that receives the computed value (self-targeting).
5961
- **Variables:** \`formValue\`, \`fieldValue\`, \`externalData\` (see topic: external-data)`,
5967
+ **Variables:** \`formValue\`, \`fieldValue\`, \`externalData\` (see topic: external-data)
5968
+ **For deriving component properties** (minDate, options, label): see topic \`property-derivation\``,
5962
5969
  full: `# Value Derivation (Computed Fields)
5963
5970
 
5964
5971
  Derivations are always defined ON the field that receives the computed value (self-targeting).
@@ -6040,7 +6047,9 @@ derivation: \`(() => {
6040
6047
  const price = formValue.unitPrice || 0;
6041
6048
  return qty * price;
6042
6049
  })()\`
6043
- \`\`\``
6050
+ \`\`\`
6051
+
6052
+ **See also:** \`property-derivation\` topic for deriving component properties (minDate, options, label, etc.)`
6044
6053
  },
6045
6054
  "options-format": {
6046
6055
  brief: `\`\`\`typescript
@@ -6127,6 +6136,179 @@ expression: 'externalData.permissions.includes("edit")'
6127
6136
  1. **Always use optional chaining** (\`?.\`) for nested paths
6128
6137
  2. **Provide defaults** for potentially undefined values: \`formValue.count || 0\`
6129
6138
  3. **Use nullish coalescing** (\`??\`) when 0 or empty string are valid: \`formValue.score ?? 'N/A'\``
6139
+ },
6140
+ "property-derivation": {
6141
+ brief: `\`\`\`typescript
6142
+ // Derive endDate's minDate from startDate value
6143
+ logic: [{ type: 'propertyDerivation', targetProperty: 'minDate', expression: 'formValue.startDate' }]
6144
+
6145
+ // Derive select options from another field
6146
+ logic: [{ type: 'propertyDerivation', targetProperty: 'options', functionName: 'getCitiesForCountry', dependsOn: ['country'] }]
6147
+ \`\`\`
6148
+ Unlike value derivation (which sets the field's **value**), property derivation sets **component input properties** like minDate, options, label, placeholder, props.appearance.`,
6149
+ full: `# Property Derivation (Dynamic Field Properties)
6150
+
6151
+ Reactively derive field component properties based on form values. Unlike value derivations (which compute the field's value), property derivations compute **component input properties** like \`minDate\`, \`options\`, \`label\`, \`placeholder\`, \`props.appearance\`, etc.
6152
+
6153
+ Property derivations are self-targeting: the logic is placed on the field whose property should be derived.
6154
+
6155
+ ## Basic Syntax
6156
+
6157
+ \`\`\`typescript
6158
+ {
6159
+ key: 'endDate',
6160
+ type: 'datepicker',
6161
+ label: 'End Date',
6162
+ logic: [{
6163
+ type: 'propertyDerivation',
6164
+ targetProperty: 'minDate',
6165
+ expression: 'formValue.startDate',
6166
+ }]
6167
+ }
6168
+ \`\`\`
6169
+
6170
+ When \`startDate\` changes, the \`minDate\` property on the \`endDate\` datepicker is automatically updated.
6171
+
6172
+ ## Derivation Sources
6173
+
6174
+ ### Expression-Based
6175
+ \`\`\`typescript
6176
+ logic: [{
6177
+ type: 'propertyDerivation',
6178
+ targetProperty: 'minDate',
6179
+ expression: 'formValue.startDate',
6180
+ }]
6181
+ \`\`\`
6182
+
6183
+ ### Static Value
6184
+ \`\`\`typescript
6185
+ logic: [{
6186
+ type: 'propertyDerivation',
6187
+ targetProperty: 'label',
6188
+ value: 'Mobile Phone',
6189
+ condition: { type: 'fieldValue', fieldPath: 'contactType', operator: 'equals', value: 'mobile' },
6190
+ }]
6191
+ \`\`\`
6192
+
6193
+ ### Custom Function
6194
+ \`\`\`typescript
6195
+ // Register in customFnConfig
6196
+ customFnConfig: {
6197
+ propertyDerivations: {
6198
+ getCitiesForCountry: (ctx) => {
6199
+ const cities = { 'US': [{ label: 'NYC', value: 'nyc' }], 'DE': [{ label: 'Berlin', value: 'berlin' }] };
6200
+ return cities[ctx.formValue.country as string] ?? [];
6201
+ },
6202
+ },
6203
+ }
6204
+
6205
+ // Use in field config
6206
+ {
6207
+ key: 'city',
6208
+ type: 'select',
6209
+ label: 'City',
6210
+ logic: [{
6211
+ type: 'propertyDerivation',
6212
+ targetProperty: 'options',
6213
+ functionName: 'getCitiesForCountry',
6214
+ dependsOn: ['country'],
6215
+ }]
6216
+ }
6217
+ \`\`\`
6218
+
6219
+ ## Supported Target Properties
6220
+
6221
+ ### Simple Properties (1 level)
6222
+ \`minDate\`, \`maxDate\`, \`options\`, \`label\`, \`placeholder\`, \`hint\`, \`disabled\`, \`readonly\`, \`required\`, \`rows\`, \`cols\`, etc.
6223
+
6224
+ ### Nested Properties (max 2 levels)
6225
+ \`props.appearance\`, \`props.color\`, \`props.variant\`, \`meta.autocomplete\`, etc.
6226
+
6227
+ \u26A0\uFE0F Deeper nesting (3+ levels) is **not supported**.
6228
+
6229
+ ## Trigger Timing
6230
+
6231
+ | Trigger | Description | Use Case |
6232
+ |-------------|---------------------------------------|-----------------------------------|
6233
+ | \`onChange\` | Immediately on change (default) | Date constraints, dynamic options |
6234
+ | \`debounced\` | After value stabilizes | Expensive lookups, API calls |
6235
+
6236
+ \`\`\`typescript
6237
+ logic: [{
6238
+ type: 'propertyDerivation',
6239
+ targetProperty: 'options',
6240
+ functionName: 'searchProducts',
6241
+ trigger: 'debounced',
6242
+ debounceMs: 300,
6243
+ dependsOn: ['searchQuery'],
6244
+ }]
6245
+ \`\`\`
6246
+
6247
+ ## Conditional Property Derivation
6248
+
6249
+ \`\`\`typescript
6250
+ logic: [{
6251
+ type: 'propertyDerivation',
6252
+ targetProperty: 'label',
6253
+ value: 'Company Email',
6254
+ condition: { type: 'fieldValue', fieldPath: 'accountType', operator: 'equals', value: 'business' },
6255
+ }]
6256
+ \`\`\`
6257
+
6258
+ ## Array Fields
6259
+
6260
+ Inside arrays, \`formValue\` is scoped to the current array item:
6261
+ \`\`\`typescript
6262
+ {
6263
+ key: 'lineItems',
6264
+ type: 'array',
6265
+ fields: [{
6266
+ key: 'item',
6267
+ type: 'group',
6268
+ fields: [
6269
+ { key: 'startDate', type: 'datepicker', label: 'Start' },
6270
+ {
6271
+ key: 'endDate',
6272
+ type: 'datepicker',
6273
+ label: 'End',
6274
+ logic: [{
6275
+ type: 'propertyDerivation',
6276
+ targetProperty: 'minDate',
6277
+ expression: 'formValue.startDate', // Scoped to current array item
6278
+ }]
6279
+ }
6280
+ ]
6281
+ }]
6282
+ }
6283
+ \`\`\`
6284
+
6285
+ ## Key Differences from Value Derivation
6286
+
6287
+ | Aspect | Value Derivation | Property Derivation |
6288
+ |--------|-----------------|---------------------|
6289
+ | Sets | Field's form value | Component input property |
6290
+ | Type | \`type: 'derivation'\` | \`type: 'propertyDerivation'\` |
6291
+ | Target | Implicit (self) | \`targetProperty: 'minDate'\` |
6292
+ | Shorthand | \`derivation: 'expr'\` | None (must use logic block) |
6293
+ | Chaining | Topologically sorted | No chaining (single pass) |
6294
+ | Functions | \`customFnConfig.derivations\` | \`customFnConfig.propertyDerivations\` |
6295
+
6296
+ ## PropertyDerivationLogicConfig Interface
6297
+
6298
+ \`\`\`typescript
6299
+ interface PropertyDerivationLogicConfig {
6300
+ type: 'propertyDerivation';
6301
+ targetProperty: string; // Property to set (e.g., 'minDate', 'options')
6302
+ debugName?: string; // For logging/debugging
6303
+ condition?: ConditionalExpression | boolean; // When to apply (default: true)
6304
+ value?: unknown; // Static value (mutually exclusive)
6305
+ expression?: string; // JavaScript expression (mutually exclusive)
6306
+ functionName?: string; // Custom function name (mutually exclusive)
6307
+ dependsOn?: string[]; // Explicit field dependencies
6308
+ trigger?: 'onChange' | 'debounced'; // Evaluation timing (default: 'onChange')
6309
+ debounceMs?: number; // Debounce duration (default: 500)
6310
+ }
6311
+ \`\`\``
6130
6312
  },
6131
6313
  "external-data": {
6132
6314
  brief: `\`\`\`typescript
@@ -6362,34 +6544,36 @@ validators: [{
6362
6544
  // ========== PATTERNS & RULES ==========
6363
6545
  "logic-matrix": {
6364
6546
  brief: `**Containers:** group/row/array have NO logic (apply to children)
6365
- **Page:** hidden only | **Value fields:** all logic types | **Buttons:** hidden, disabled`,
6547
+ **Page:** hidden only | **Value fields:** all logic types incl. propertyDerivation | **Buttons:** hidden, disabled`,
6366
6548
  full: `# Logic Support Matrix
6367
6549
 
6368
- | Field Type | hidden | disabled | required | readonly | derivation |
6369
- |----------------|--------|----------|----------|----------|------------|
6370
- | page | Y | N | N | N | N |
6371
- | group | N | N | N | N | N |
6372
- | row | N | N | N | N | N |
6373
- | array | N | N | N | N | N |
6374
- | input | Y | Y | Y | Y | Y |
6375
- | select | Y | Y | Y | Y | Y |
6376
- | checkbox | Y | Y | Y | Y | Y |
6377
- | radio | Y | Y | Y | Y | Y |
6378
- | multi-checkbox | Y | Y | Y | Y | Y |
6379
- | textarea | Y | Y | Y | Y | Y |
6380
- | datepicker | Y | Y | Y | Y | Y |
6381
- | toggle | Y | Y | Y | Y | Y |
6382
- | slider | Y | Y | Y | Y | Y |
6383
- | hidden | N | N | N | N | N |
6384
- | text | Y | N | N | N | N |
6385
- | button/submit | Y | Y | N | N | N |
6386
- | next/previous | Y | Y | N | N | N |
6550
+ | Field Type | hidden | disabled | required | readonly | derivation | propertyDerivation |
6551
+ |----------------|--------|----------|----------|----------|------------|--------------------|
6552
+ | page | Y | N | N | N | N | N |
6553
+ | group | N | N | N | N | N | N |
6554
+ | row | N | N | N | N | N | N |
6555
+ | array | N | N | N | N | N | N |
6556
+ | input | Y | Y | Y | Y | Y | Y |
6557
+ | select | Y | Y | Y | Y | Y | Y |
6558
+ | checkbox | Y | Y | Y | Y | Y | Y |
6559
+ | radio | Y | Y | Y | Y | Y | Y |
6560
+ | multi-checkbox | Y | Y | Y | Y | Y | Y |
6561
+ | textarea | Y | Y | Y | Y | Y | Y |
6562
+ | datepicker | Y | Y | Y | Y | Y | Y |
6563
+ | toggle | Y | Y | Y | Y | Y | Y |
6564
+ | slider | Y | Y | Y | Y | Y | Y |
6565
+ | hidden | N | N | N | N | N | N |
6566
+ | text | Y | N | N | N | N | Y |
6567
+ | button/submit | Y | Y | N | N | N | N |
6568
+ | next/previous | Y | Y | N | N | N | N |
6387
6569
 
6388
6570
  **Key takeaways:**
6389
6571
  - Containers (group, row, array) do NOT support logic - apply to children instead
6390
6572
  - Page only supports \`hidden\` logic (for conditional pages)
6391
6573
  - Hidden fields have NO logic support at all
6392
- - Value fields (input, select, etc.) support ALL logic types`
6574
+ - Value fields (input, select, etc.) support ALL logic types including \`propertyDerivation\`
6575
+ - \`propertyDerivation\` sets component input properties (e.g., \`minDate\`, \`options\`), NOT the field's form value
6576
+ - Text (display) fields support \`propertyDerivation\` for dynamic labels`
6393
6577
  },
6394
6578
  "context-api": {
6395
6579
  brief: `**Expressions:** \`formValue.field\`, \`fieldValue\`
@@ -7148,6 +7332,15 @@ var TOPIC_ALIASES = {
7148
7332
  computed: "derivation",
7149
7333
  calculate: "derivation",
7150
7334
  expression: "derivation",
7335
+ // Property derivation aliases
7336
+ "property-derive": "property-derivation",
7337
+ propertyderivation: "property-derivation",
7338
+ "dynamic-properties": "property-derivation",
7339
+ "derived-properties": "property-derivation",
7340
+ "dynamic-options": "property-derivation",
7341
+ "dynamic-label": "property-derivation",
7342
+ mindate: "property-derivation",
7343
+ maxdate: "property-derivation",
7151
7344
  // Validation aliases
7152
7345
  validators: "validation",
7153
7346
  required: "validation",
@@ -7251,6 +7444,7 @@ function getTopicList() {
7251
7444
  "validation-messages",
7252
7445
  "conditional",
7253
7446
  "derivation",
7447
+ "property-derivation",
7254
7448
  "options-format",
7255
7449
  "expression-variables",
7256
7450
  "async-validators",
@@ -7357,14 +7551,14 @@ Field types: input, select, slider, radio, checkbox, textarea, datepicker, toggl
7357
7551
 
7358
7552
  Containers: group, row, array, page
7359
7553
 
7360
- Concepts: validation, conditional, derivation, options-format, expression-variables, async-validators
7554
+ Concepts: validation, conditional, derivation, property-derivation, options-format, expression-variables, async-validators
7361
7555
 
7362
7556
  Patterns: field-placement, logic-matrix, context-api, containers, multi-page-gotchas
7363
7557
 
7364
7558
  Use topic="list" to see all available topics.`,
7365
7559
  {
7366
7560
  topic: z54.string().describe(
7367
- 'Topic to look up: field types (input, select, hidden, group, row, array, page), concepts (validation, conditional, derivation, options-format), patterns (golden-path, pitfalls, multi-page-gotchas), or "list" to see all topics'
7561
+ 'Topic to look up: field types (input, select, hidden, group, row, array, page), concepts (validation, conditional, derivation, property-derivation, options-format), patterns (golden-path, pitfalls, multi-page-gotchas), or "list" to see all topics'
7368
7562
  ),
7369
7563
  depth: z54.enum(["brief", "full", "schema"]).default("full").describe("brief=quick syntax (~20 lines), full=complete docs with examples, schema=include JSON schema"),
7370
7564
  uiIntegration: z54.enum(UI_INTEGRATIONS2).optional().describe("Filter UI-specific info (only with depth=schema). material, bootstrap, primeng, ionic")
@@ -8399,6 +8593,426 @@ These will cause validation errors:
8399
8593
  { key: 'roleId', type: 'hidden', value: 42 } // number
8400
8594
  { key: 'isActive', type: 'hidden', value: true } // boolean
8401
8595
  { key: 'tagIds', type: 'hidden', value: [1, 2, 3] } // array
8596
+ \`\`\``
8597
+ },
8598
+ "property-derivation": {
8599
+ description: "Derive field properties (minDate, options, label) from form values",
8600
+ minimal: `import { FormConfig } from '@ng-forge/dynamic-forms';
8601
+
8602
+ const formConfig = {
8603
+ fields: [
8604
+ { key: 'startDate', type: 'datepicker', label: 'Start Date' },
8605
+ {
8606
+ key: 'endDate',
8607
+ type: 'datepicker',
8608
+ label: 'End Date',
8609
+ logic: [{
8610
+ type: 'propertyDerivation',
8611
+ targetProperty: 'minDate',
8612
+ expression: 'formValue.startDate',
8613
+ }]
8614
+ },
8615
+ { key: 'submit', type: 'submit', label: 'Submit' }
8616
+ ]
8617
+ } as const satisfies FormConfig;`,
8618
+ brief: `// Derive component properties from form values
8619
+ import { FormConfig } from '@ng-forge/dynamic-forms';
8620
+
8621
+ const formConfig = {
8622
+ fields: [
8623
+ { key: 'startDate', type: 'datepicker', label: 'Start Date' },
8624
+ {
8625
+ key: 'endDate',
8626
+ type: 'datepicker',
8627
+ label: 'End Date',
8628
+ // \u26A0\uFE0F type: 'propertyDerivation' (NOT 'derivation')
8629
+ // \u26A0\uFE0F targetProperty specifies WHICH property to set
8630
+ logic: [{
8631
+ type: 'propertyDerivation',
8632
+ targetProperty: 'minDate',
8633
+ expression: 'formValue.startDate',
8634
+ }]
8635
+ },
8636
+ {
8637
+ key: 'country',
8638
+ type: 'select',
8639
+ label: 'Country',
8640
+ options: [{ label: 'USA', value: 'US' }, { label: 'Germany', value: 'DE' }]
8641
+ },
8642
+ {
8643
+ key: 'city',
8644
+ type: 'select',
8645
+ label: 'City',
8646
+ options: [],
8647
+ // Dynamic options from custom function
8648
+ logic: [{
8649
+ type: 'propertyDerivation',
8650
+ targetProperty: 'options',
8651
+ functionName: 'getCitiesForCountry',
8652
+ dependsOn: ['country'],
8653
+ }]
8654
+ },
8655
+ { key: 'submit', type: 'submit', label: 'Submit' }
8656
+ ]
8657
+ } as const satisfies FormConfig;
8658
+
8659
+ // Key points:
8660
+ // - type: 'propertyDerivation' sets component PROPERTIES (not form value)
8661
+ // - targetProperty: which input property to set (e.g., 'minDate', 'options')
8662
+ // - Supports: expression, value, functionName (mutually exclusive)
8663
+ // - Register functions in customFnConfig.propertyDerivations`,
8664
+ full: `# Property Derivation (Dynamic Field Properties)
8665
+
8666
+ Derive field component properties reactively based on form values.
8667
+
8668
+ \`\`\`typescript
8669
+ import { FormConfig } from '@ng-forge/dynamic-forms';
8670
+
8671
+ const formConfig = {
8672
+ fields: [
8673
+ // ========== DATE RANGE: minDate from startDate ==========
8674
+ { key: 'startDate', type: 'datepicker', label: 'Start Date' },
8675
+ {
8676
+ key: 'endDate',
8677
+ type: 'datepicker',
8678
+ label: 'End Date',
8679
+ logic: [{
8680
+ type: 'propertyDerivation',
8681
+ targetProperty: 'minDate', // Set minDate property
8682
+ expression: 'formValue.startDate', // From startDate's value
8683
+ }]
8684
+ },
8685
+
8686
+ // ========== DYNAMIC OPTIONS: cities from country ==========
8687
+ {
8688
+ key: 'country',
8689
+ type: 'select',
8690
+ label: 'Country',
8691
+ options: [
8692
+ { label: 'USA', value: 'US' },
8693
+ { label: 'Germany', value: 'DE' }
8694
+ ]
8695
+ },
8696
+ {
8697
+ key: 'city',
8698
+ type: 'select',
8699
+ label: 'City',
8700
+ options: [], // Initial empty, filled by property derivation
8701
+ logic: [{
8702
+ type: 'propertyDerivation',
8703
+ targetProperty: 'options',
8704
+ functionName: 'getCitiesForCountry',
8705
+ dependsOn: ['country'],
8706
+ }]
8707
+ },
8708
+
8709
+ // ========== CONDITIONAL LABEL ==========
8710
+ {
8711
+ key: 'phone',
8712
+ type: 'input',
8713
+ label: 'Phone',
8714
+ logic: [{
8715
+ type: 'propertyDerivation',
8716
+ targetProperty: 'label',
8717
+ value: 'Mobile Phone',
8718
+ condition: {
8719
+ type: 'fieldValue',
8720
+ fieldPath: 'contactType',
8721
+ operator: 'equals',
8722
+ value: 'mobile'
8723
+ },
8724
+ }]
8725
+ },
8726
+
8727
+ // ========== NESTED PROPERTY ==========
8728
+ {
8729
+ key: 'notes',
8730
+ type: 'textarea',
8731
+ label: 'Notes',
8732
+ logic: [{
8733
+ type: 'propertyDerivation',
8734
+ targetProperty: 'props.appearance', // Dot-notation for nested
8735
+ expression: 'formValue.isPremium ? "fill" : "outline"',
8736
+ }]
8737
+ },
8738
+
8739
+ { key: 'submit', type: 'submit', label: 'Submit' }
8740
+ ]
8741
+ } as const satisfies FormConfig;
8742
+ \`\`\`
8743
+
8744
+ ## Custom Function Registration
8745
+
8746
+ \`\`\`typescript
8747
+ // customFnConfig is a property of FormConfig, not a provider option
8748
+ const formConfig = {
8749
+ customFnConfig: {
8750
+ propertyDerivations: {
8751
+ getCitiesForCountry: (ctx) => {
8752
+ const cities: Record<string, { label: string; value: string }[]> = {
8753
+ 'US': [{ label: 'New York', value: 'nyc' }, { label: 'LA', value: 'la' }],
8754
+ 'DE': [{ label: 'Berlin', value: 'berlin' }, { label: 'Munich', value: 'munich' }],
8755
+ };
8756
+ return cities[ctx.formValue.country as string] ?? [];
8757
+ },
8758
+ },
8759
+ },
8760
+ fields: [
8761
+ // ... fields with propertyDerivation logic referencing 'getCitiesForCountry'
8762
+ ],
8763
+ } as const satisfies FormConfig;
8764
+ \`\`\`
8765
+
8766
+ ## Key Differences from Value Derivation
8767
+
8768
+ | Feature | \`type: 'derivation'\` | \`type: 'propertyDerivation'\` |
8769
+ |---------|----------------------|-------------------------------|
8770
+ | Sets | Field's form value | Component property |
8771
+ | Target | Implicit (self) | \`targetProperty: 'minDate'\` |
8772
+ | Shorthand | \`derivation: 'expr'\` | None |
8773
+ | Functions | \`customFnConfig.derivations\` | \`customFnConfig.propertyDerivations\` |`,
8774
+ explained: `# Property Derivation - Complete Explanation
8775
+
8776
+ ## What is Property Derivation?
8777
+
8778
+ Property derivation allows you to **reactively update component input properties** based on form state. While value derivations (\`type: 'derivation'\`) compute a field's form value, property derivations (\`type: 'propertyDerivation'\`) compute the field's component properties like \`minDate\`, \`options\`, \`label\`, \`placeholder\`, \`props.appearance\`, etc.
8779
+
8780
+ ## When to Use Property Derivation
8781
+
8782
+ Use property derivation when:
8783
+ - **Date constraints**: endDate's minDate should follow startDate
8784
+ - **Dynamic options**: City options depend on selected country
8785
+ - **Dynamic labels**: Field label changes based on another field
8786
+ - **Dynamic appearance**: Input style changes based on form state
8787
+ - **Conditional placeholders**: Placeholder text depends on context
8788
+
8789
+ ## Syntax
8790
+
8791
+ \`\`\`typescript
8792
+ {
8793
+ key: 'endDate',
8794
+ type: 'datepicker',
8795
+ label: 'End Date',
8796
+ logic: [{
8797
+ type: 'propertyDerivation', // \u26A0\uFE0F NOT 'derivation'!
8798
+ targetProperty: 'minDate', // Which property to set
8799
+ expression: 'formValue.startDate', // How to compute it
8800
+ }]
8801
+ }
8802
+ \`\`\`
8803
+
8804
+ ## Three Ways to Compute Values
8805
+
8806
+ ### 1. Expression (inline JavaScript)
8807
+ \`\`\`typescript
8808
+ logic: [{
8809
+ type: 'propertyDerivation',
8810
+ targetProperty: 'minDate',
8811
+ expression: 'formValue.startDate', // Access form values
8812
+ }]
8813
+ \`\`\`
8814
+
8815
+ ### 2. Static Value (with condition)
8816
+ \`\`\`typescript
8817
+ logic: [{
8818
+ type: 'propertyDerivation',
8819
+ targetProperty: 'label',
8820
+ value: 'Business Email', // Fixed value
8821
+ condition: { type: 'fieldValue', fieldPath: 'type', operator: 'equals', value: 'business' },
8822
+ }]
8823
+ \`\`\`
8824
+
8825
+ ### 3. Custom Function (for complex logic)
8826
+ \`\`\`typescript
8827
+ // In form config
8828
+ customFnConfig: {
8829
+ propertyDerivations: {
8830
+ getCitiesForCountry: (ctx) => {
8831
+ // ctx.formValue contains all form values
8832
+ // ctx.externalData contains external signals (unwrapped)
8833
+ return lookupCities(ctx.formValue.country);
8834
+ },
8835
+ },
8836
+ }
8837
+
8838
+ // In field
8839
+ logic: [{
8840
+ type: 'propertyDerivation',
8841
+ targetProperty: 'options',
8842
+ functionName: 'getCitiesForCountry',
8843
+ dependsOn: ['country'], // \u26A0\uFE0F Recommended for custom functions!
8844
+ }]
8845
+ \`\`\`
8846
+
8847
+ ## Target Property Formats
8848
+
8849
+ ### Simple properties (1 level)
8850
+ \`\`\`typescript
8851
+ targetProperty: 'minDate' // Direct property
8852
+ targetProperty: 'options' // Array of options
8853
+ targetProperty: 'label' // Field label
8854
+ targetProperty: 'placeholder' // Field placeholder
8855
+ targetProperty: 'hint' // Hint text
8856
+ \`\`\`
8857
+
8858
+ ### Nested properties (2 levels max)
8859
+ \`\`\`typescript
8860
+ targetProperty: 'props.appearance' // Nested in props
8861
+ targetProperty: 'props.color' // Material color
8862
+ targetProperty: 'meta.autocomplete' // Custom metadata
8863
+ \`\`\`
8864
+
8865
+ ### \u274C Not supported (3+ levels)
8866
+ \`\`\`typescript
8867
+ targetProperty: 'props.nested.deep' // \u274C Too deep!
8868
+ \`\`\`
8869
+
8870
+ ## Trigger Timing
8871
+
8872
+ \`\`\`typescript
8873
+ // Default: evaluate immediately on form value change
8874
+ logic: [{
8875
+ type: 'propertyDerivation',
8876
+ targetProperty: 'options',
8877
+ expression: '...',
8878
+ trigger: 'onChange', // default
8879
+ }]
8880
+
8881
+ // Debounced: wait for typing to stop
8882
+ logic: [{
8883
+ type: 'propertyDerivation',
8884
+ targetProperty: 'options',
8885
+ functionName: 'searchProducts',
8886
+ trigger: 'debounced',
8887
+ debounceMs: 300,
8888
+ dependsOn: ['searchQuery'],
8889
+ }]
8890
+ \`\`\`
8891
+
8892
+ ## Array Field Support
8893
+
8894
+ Inside arrays, \`formValue\` is scoped to the current array item:
8895
+
8896
+ \`\`\`typescript
8897
+ {
8898
+ key: 'lineItems',
8899
+ type: 'array',
8900
+ fields: [{
8901
+ key: 'item', type: 'group',
8902
+ fields: [
8903
+ { key: 'startDate', type: 'datepicker', label: 'Start' },
8904
+ {
8905
+ key: 'endDate', type: 'datepicker', label: 'End',
8906
+ logic: [{
8907
+ type: 'propertyDerivation',
8908
+ targetProperty: 'minDate',
8909
+ expression: 'formValue.startDate', // Refers to THIS item's startDate
8910
+ }]
8911
+ }
8912
+ ]
8913
+ }]
8914
+ }
8915
+ \`\`\`
8916
+
8917
+ ## Dependencies
8918
+
8919
+ ### Automatic (for expressions)
8920
+ Dependencies are auto-extracted from expressions:
8921
+ \`\`\`typescript
8922
+ expression: 'formValue.startDate' // Automatically depends on 'startDate'
8923
+ \`\`\`
8924
+
8925
+ ### Explicit (for custom functions)
8926
+ \`\`\`typescript
8927
+ functionName: 'getCities',
8928
+ dependsOn: ['country'], // Only re-evaluate when 'country' changes
8929
+ \`\`\`
8930
+
8931
+ ### Wildcard (default for functions without dependsOn)
8932
+ Functions without \`dependsOn\` re-evaluate on ANY form change. Add \`dependsOn\` for performance.
8933
+
8934
+ ## Complete Example
8935
+
8936
+ \`\`\`typescript
8937
+ import { FormConfig } from '@ng-forge/dynamic-forms';
8938
+
8939
+ const travelForm = {
8940
+ customFnConfig: {
8941
+ propertyDerivations: {
8942
+ getCitiesForCountry: (ctx) => {
8943
+ const cities: Record<string, { label: string; value: string }[]> = {
8944
+ 'US': [{ label: 'New York', value: 'nyc' }, { label: 'LA', value: 'la' }],
8945
+ 'DE': [{ label: 'Berlin', value: 'berlin' }],
8946
+ };
8947
+ return cities[ctx.formValue.country as string] ?? [];
8948
+ },
8949
+ },
8950
+ },
8951
+ fields: [
8952
+ {
8953
+ key: 'country',
8954
+ type: 'select',
8955
+ label: 'Country',
8956
+ options: [
8957
+ { label: 'USA', value: 'US' },
8958
+ { label: 'Germany', value: 'DE' },
8959
+ ],
8960
+ },
8961
+ {
8962
+ key: 'city',
8963
+ type: 'select',
8964
+ label: 'City',
8965
+ options: [],
8966
+ logic: [{
8967
+ type: 'propertyDerivation',
8968
+ targetProperty: 'options',
8969
+ functionName: 'getCitiesForCountry',
8970
+ dependsOn: ['country'],
8971
+ }],
8972
+ },
8973
+ { key: 'startDate', type: 'datepicker', label: 'Travel Start' },
8974
+ {
8975
+ key: 'endDate',
8976
+ type: 'datepicker',
8977
+ label: 'Travel End',
8978
+ logic: [{
8979
+ type: 'propertyDerivation',
8980
+ targetProperty: 'minDate',
8981
+ expression: 'formValue.startDate',
8982
+ }],
8983
+ },
8984
+ { key: 'submit', type: 'submit', label: 'Book Trip' },
8985
+ ],
8986
+ } as const satisfies FormConfig;
8987
+ \`\`\`
8988
+
8989
+ ## Common Mistakes
8990
+
8991
+ \u274C Confusing with value derivation:
8992
+ \`\`\`typescript
8993
+ // WRONG - 'derivation' changes the form value, not a property
8994
+ logic: [{ type: 'derivation', expression: 'formValue.startDate' }]
8995
+
8996
+ // CORRECT - 'propertyDerivation' changes a component property
8997
+ logic: [{ type: 'propertyDerivation', targetProperty: 'minDate', expression: 'formValue.startDate' }]
8998
+ \`\`\`
8999
+
9000
+ \u274C Missing targetProperty:
9001
+ \`\`\`typescript
9002
+ // WRONG - must specify which property to set
9003
+ logic: [{ type: 'propertyDerivation', expression: '...' }]
9004
+
9005
+ // CORRECT
9006
+ logic: [{ type: 'propertyDerivation', targetProperty: 'options', expression: '...' }]
9007
+ \`\`\`
9008
+
9009
+ \u274C Using wrong customFnConfig key:
9010
+ \`\`\`typescript
9011
+ // WRONG - derivations is for value derivation functions
9012
+ customFnConfig: { derivations: { getCities: ... } }
9013
+
9014
+ // CORRECT - propertyDerivations is for property derivation functions
9015
+ customFnConfig: { propertyDerivations: { getCities: ... } }
8402
9016
  \`\`\``
8403
9017
  },
8404
9018
  // ========== STANDARD PATTERNS ==========
@@ -9045,7 +9659,7 @@ function getPatternList() {
9045
9659
  "minimal-validation",
9046
9660
  "minimal-hidden"
9047
9661
  ],
9048
- "Standard Patterns": ["derivation", "multi-page", "conditional", "validation"]
9662
+ "Standard Patterns": ["derivation", "property-derivation", "multi-page", "conditional", "validation"]
9049
9663
  };
9050
9664
  for (const [category, patterns] of Object.entries(categories)) {
9051
9665
  lines.push(`## ${category}`);
@@ -9076,13 +9690,13 @@ Minimal patterns (~20-50 lines):
9076
9690
  - minimal-validation: Password confirmation
9077
9691
  - minimal-hidden: Hidden fields in multi-page
9078
9692
 
9079
- Standard patterns: derivation, multi-page, conditional, validation
9693
+ Standard patterns: derivation, property-derivation, multi-page, conditional, validation
9080
9694
 
9081
9695
  Use pattern="list" to see all available patterns.
9082
9696
  Use depth="minimal" for code-only output (no markdown).`,
9083
9697
  {
9084
9698
  pattern: z55.string().optional().describe(
9085
- 'Pattern to get: minimal-multipage, minimal-array, minimal-conditional, minimal-validation, minimal-hidden, derivation, multi-page, conditional, validation, complete, mega. Use "list" to see all.'
9699
+ 'Pattern to get: minimal-multipage, minimal-array, minimal-conditional, minimal-validation, minimal-hidden, derivation, property-derivation, multi-page, conditional, validation, complete, mega. Use "list" to see all.'
9086
9700
  ),
9087
9701
  depth: z55.enum(["minimal", "brief", "full", "explained"]).default("full").describe(
9088
9702
  "minimal=code only (~20-50 lines), brief=code+summary, full=code+comments (default), explained=code+detailed explanation"