@anglr/dynamic
v1.0.1
Published
Contains code for generating dynamic content from metadata
Readme
Angular Dynamic (@anglr/dynamic)
Angular library for building dynamic content from JSON metadata. Pages are described as a layout (a tree of components with options) and their logic as relations (a graph that connects component outputs to component inputs). Both are plain JSON, so they can be stored on a server, rendered at runtime and edited in the built-in drag & drop layout editor and relations editor. Everything is package-based: components come from lazily loaded packages of dynamic items, and you can add your own packages next to the built-in ones.
| Entry point | Description |
| --- | --- |
| @anglr/dynamic | Core: provideDynamic(), feature system, dynamic item loading, packages (PackageManager, PackageSource), MetadataStorage, MetadataHistoryManager, DefaultsOverride, EditorHotkeys, extension base class, code editor |
| @anglr/dynamic/layout | Layout runtime: *layoutComponentRenderer, LayoutComponentBase, LayoutRenderer, ComponentStylingExtension, withLayoutRuntime() |
| @anglr/dynamic/layout-editor | Layout editor: <layout-editor>, editor metadata decorators, properties controls, property type controls, withLayoutEditor() |
| @anglr/dynamic/relations | Relations runtime: RelationsManager, RelationsProcessor, @DynamicOutput(), @PureRelationsComponent(), RelationsRegistrationExtension, withRelationsRuntime() |
| @anglr/dynamic/relations-editor | Relations editor: <relations-editor>, RelationsNodeBase, node building blocks, withRelationsEditor(), static components |
| @anglr/dynamic/layout-relations | Glue between layout and relations: withLayoutRelationsRuntime(), withLayoutRelationsEditor(), LayoutManager, custom components and custom relations |
| @anglr/dynamic/relations-debugger | Step-by-step visualizer of relations data transfers (experimental) |
| @anglr/dynamic/basic-components | Built-in package basic-components: layout containers, texts, buttons and logical/data relations nodes |
| @anglr/dynamic/form | Built-in package form-components: form fields and FormComponentControlBuilder |
| @anglr/dynamic/material-components | Built-in package material-components: Angular Material form fields, tabs, expansion panel |
| @anglr/dynamic/css-components | Built-in package css-components: scoped style block |
| @anglr/dynamic/handlebars-components | Built-in package handlebars-components: data rendered by handlebars templates |
| @anglr/dynamic/rest-components | Built-in package rest-components: REST request relations node |
| @anglr/dynamic/tinymce-components | Built-in package tinymce-components: rich text block edited by TinyMCE |
| @anglr/dynamic/math-components | Built-in package math-components: math relations nodes |
| @anglr/dynamic/grid-components | Built-in package grid-components: data table based on @anglr/grid |
| @anglr/dynamic/styles | SCSS mixins and functions (buildThemeColors, buildThemeCss, buildTheme, defineTheme) |
| @anglr/dynamic/styles/themes/* | SCSS themes dark and light |
| @anglr/dynamic/typings/transformData/monaco-type, @anglr/dynamic/typings/state/monaco-type | Type definitions (as text) used by code editors of the transformData and state relations nodes |
- Resources
- Installation
- Quick Start
- Features
- Core concepts
- Providers and setup
- Creating and using dynamic items
- Customizing properties of dynamic items
- Layout
- Relations
- Extensibility
- Styling
- Samples
- Layout with relations
- ⭐ Creating your own package of dynamic items
- Custom layout component with editable properties
- Component that is both layout and relations
- Pure relations node
- Layout editor
- Relations editor
- Custom property editor
- Dynamic forms
- Loading metadata from storage
- Overriding defaults
- Static components in relations
- Custom components
- Usage notes
- Dev instructions
- License
Resources
- API reference: https://ressurectit.github.io/#/content/api/ng-dynamic/dynamic
- API layout reference: https://ressurectit.github.io/#/content/api/ng-dynamic-layout/dynamic-layout
- API layout editor reference: https://ressurectit.github.io/#/content/api/ng-dynamic-layout-editor/dynamic-layout-editor
- API relations reference: https://ressurectit.github.io/#/content/api/ng-dynamic-relations/dynamic-relations
- API relations editor reference: https://ressurectit.github.io/#/content/api/ng-dynamic-relations-editor/dynamic-relations-editor
- API basic components reference: https://ressurectit.github.io/#/content/api/ng-dynamic-basic-components/dynamic-basic-components
- API math components reference: https://ressurectit.github.io/#/content/api/ng-dynamic-math-components/dynamic-math-components
- Demo site: https://ressurectit.github.io
Installation
npm install @anglr/dynamicDependencies
These are regular dependencies of the package, installed together with it: @angular/core, @angular/common, @angular/forms, @angular/cdk, @angular/material, @anglr/common, @jscrpt/common, @ng-dnd/core, react-dnd-html5-backend, angular2-hotkeys, monaco-editor, d3, lodash-es, rxjs, tslib.
Optional dependencies
Some built-in packages wrap third-party libraries. Install the optional dependency only when you use the entry point that needs it.
| Optional dependency | Needed by |
| --- | --- |
| postcss, postcss-prefix-selector | @anglr/dynamic/css-components |
| handlebars | @anglr/dynamic/handlebars-components |
| @anglr/rest | @anglr/dynamic/rest-components |
| @tinymce/tinymce-angular, tinymce | @anglr/dynamic/tinymce-components |
| @anglr/grid | @anglr/dynamic/grid-components |
Project setup
Build loaders. The core imports monaco-editor (which pulls in a .ttf icon font) and @anglr/dynamic/basic-components imports .monaco-type files. The Angular build needs loaders for both, in angular.json → architect.build.options:
"loader":
{
".monaco-type": "text",
".ttf": "file"
},TypeScript. The decorators of the library (@DynamicOutput(), @LayoutPropertyName(), …) are property decorators that define accessors on the prototype. They need legacy decorators and class fields that don't shadow prototype accessors (tsconfig.json → compilerOptions):
"experimentalDecorators": true,"useDefineForClassFields": false,Monaco editor assets. Code editors (code properties controls, the state and transformData nodes) load Monaco at runtime from the path in the MONACO_EDITOR_RESOURCES_PATH token (default 'monaco-editor/vs'). Serve node_modules/monaco-editor/min as the monaco-editor asset folder, or provide the token with your own path. Rendering layouts without code editors doesn't need these assets.
TinyMCE assets (only for tinymce-components). The rich text editor loads tinymce.min.js from the global ngDynamicTinymcePath (default 'tinymce'), so serve TinyMCE assets under that path.
Application-level providers. Runtime rendering only needs what provideDynamic() provides (LOGGER and ProgressIndicatorService from @anglr/common have root defaults). The editors use more services from @anglr/common, which must be provided once in the application:
| Provider | Needed for |
| --- | --- |
| providePermanentStorage(LocalPermanentStorage) (@anglr/common, @anglr/common/store) | Layout editor (properties editor state, live events), withPackageManager('STORAGE_NAME') |
| providePosition(FloatingUiDomPosition) (@anglr/common, @anglr/common/floating-ui) | Layout editor (drop placeholders, overlays), relations debugger |
| TitledDialogService + importProvidersFrom(MatDialogModule) (@anglr/common/material) | Relations editor node properties, code editor dialogs |
| HotkeyModule.forRoot() (angular2-hotkeys) + AppHotkeysService (@anglr/common/hotkeys) | withEditorHotkeys() |
| importProvidersFrom(DndModule.forRoot({backend: HTML5Backend})) (@ng-dnd/core, react-dnd-html5-backend) | Layout editor drag & drop |
The drag & drop provider can live on the route that contains the editors:
import {importProvidersFrom} from '@angular/core';
import {Route} from '@angular/router';
import {DndModule} from '@ng-dnd/core';
import {HTML5Backend} from 'react-dnd-html5-backend'; providers:
[
//drag and drop used by layout editor, required only for editors
importProvidersFrom(DndModule.forRoot({backend: HTML5Backend})),
],Styles. The editors and the built-in components need the library CSS, see Styling.
Build-time globals (optional). The library reads three globals that can be set with the define option of the Angular build:
| Global | Default | Description |
| --- | --- | --- |
| ngDesignerMetadata | true | When false, the editor metadata decorators (@LayoutEditorMetadata, @RelationsEditorMetadata, @LayoutProperty*) become no-ops, so editor metadata isn't loaded in runtime-only builds |
| ngRelationsDebugger | true | When false, the debugger hooks of the relations runtime are skipped |
| ngDynamicTinymcePath | 'tinymce' | Path to TinyMCE assets |
Quick Start
Render layout metadata with the built-in basic-components package. provideDynamic() is usually placed in the providers of the component that renders the layout, so every page gets its own dynamic scope.
import {Component, ChangeDetectionStrategy} from '@angular/core';
import {provideDynamic} from '@anglr/dynamic';
import {LayoutComponentMetadata, LayoutComponentRendererDirective, withLayoutRuntime} from '@anglr/dynamic/layout';
import {withBasicComponents} from '@anglr/dynamic/basic-components';
import {quickStartLayout} from './quickStart.data';
/**
* Renders layout metadata at runtime
*/
@Component(
{
selector: 'quick-start-sample',
templateUrl: 'quickStart.component.html',
imports:
[
LayoutComponentRendererDirective,
],
providers:
[
provideDynamic(withLayoutRuntime(),
withBasicComponents()),
],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class QuickStartComponent
{
//######################### protected properties - template bindings #########################
/**
* Layout metadata to be rendered
*/
protected metadata: LayoutComponentMetadata = quickStartLayout;
}<ng-container *layoutComponentRenderer="metadata"/>The metadata is a tree of {id, package, name, options} nodes. Containers keep their children inside options (children for stackPanel). Styling options (textStyling) and options of the parent's child extension (flex from stackPanel) live in the same options object:
import {LayoutComponentMetadata} from '@anglr/dynamic/layout';
/**
* Layout metadata rendered by quick start sample, usually loaded from server
*/
export const quickStartLayout: LayoutComponentMetadata =
{
id: 'stackPanel-root',
displayName: 'root',
package: 'basic-components',
name: 'stackPanel',
options:
{
horizontal: false,
children:
[
{
id: 'textBlock-title',
package: 'basic-components',
name: 'textBlock',
options:
{
text: 'Hello from dynamic layout',
textStyling:
{
fontSize: '20px',
fontWeight: 700,
},
},
},
{
id: 'stackPanel-row',
package: 'basic-components',
name: 'stackPanel',
options:
{
horizontal: true,
children:
[
{
id: 'textBlock-description',
package: 'basic-components',
name: 'textBlock',
options:
{
text: 'Everything on this page is rendered from JSON metadata',
flex: '1',
},
},
{
id: 'button-ok',
package: 'basic-components',
name: 'button',
options:
{
text: 'Click me',
buttonCssClass: 'btn btn-primary',
type: 'button',
disabled: false,
},
},
],
},
},
],
},
};Features
- Metadata-driven UI – pages are JSON (
LayoutComponentMetadatatree +RelationsComponentMetadata[]graph) that can be stored anywhere and rendered with one structural directive. - Relations instead of code – component outputs are wired to component inputs in metadata; non-visual relations nodes (negation, logical AND/OR, merge, debounce, state, REST, math, …) transform data on the way.
- Visual editors – drag & drop layout editor with component palette, component tree, properties editor, undo/redo and hotkeys; relations editor with node palette and canvas.
- Package-based and lazy – every item is loaded on demand with dynamic
import(), editor metadata is loaded lazily as well and can be stripped from runtime builds. - Built-in packages – basic layout, form fields, Angular Material, scoped CSS, handlebars, REST, TinyMCE, math and
@anglr/griddata tables. - Your own packages – the same mechanism the built-in packages use is public: options interface, component, editor metadata,
type.ts, providers and onewith…()feature. - Editable properties – properties editor generated from decorated models, with built-in property types, custom properties controls and overridable defaults.
- Extensions – reusable behavior attached to items (
ComponentStylingExtensionfor CSS class, margin, padding and text styling; child extensions likeflexin stack panels). - Reuse – template blocks and custom components render stored layouts with their relations as one component.
- Swappable services – loaders, module providers, extractors, metadata storages, package manager, history manager, defaults override and renderer are all DI-based.
- Themable – SCSS themes and
--dynamic-*CSS custom properties.
Core concepts
Dynamic items
A dynamic item is anything that can be referenced from metadata and loaded on demand. It's identified by a DynamicItemSource:
| Property | Type | Description |
| --- | --- | --- |
| package | string | Name of the package that contains the item, e.g. 'basic-components' |
| name | string | Name of the item inside the package, e.g. 'stackPanel' |
Metadata of a concrete item instance (DynamicItemMetadata) adds:
| Property | Type | Description |
| --- | --- | --- |
| id | string | Unique id of the item instance |
| displayName | string (optional) | Name shown in editors |
| scope | string \| null (optional) | Id of scope used for components and relations |
There are two kinds of items, which can be combined in one class:
- Layout components (
LayoutComponent) – Angular components rendered by the layout renderer, configured byoptions. - Relations components (
RelationsComponent) – participants of relations, configured byrelationsOptions, with inputs and@DynamicOutput()outputs.
Every item is a DynamicItem, so it implements invalidateVisuals(). Optional lifecycle interfaces are DynamicOnInit (dynamicOnInit()), DynamicOnChanges (dynamicOnChanges(changes)) and DynamicAfterViewInit (dynamicAfterViewInit()).
Packages
A package is a named set of items (basic-components, form-components, your own my-components, …). Each item lives in its own folder with a type.ts module. The loader reads these exports from it:
| Export | Required | Description |
| --- | --- | --- |
| default | yes | The component class (layout) or relations class |
| extensions | no | Array of extensions applied to the item (or {extensions, childExtensions}) |
| childExtensions | no | Array of extensions applied to every child rendered inside the item |
| relations | no | Alternative export of a pure relations class |
import {ComponentStylingExtension} from '@anglr/dynamic/layout';
import {RelationsRegistrationExtension} from '@anglr/dynamic/relations';
import {CounterComponent} from './counter.component';
export default CounterComponent;
export const extensions = [ComponentStylingExtension, RelationsRegistrationExtension];A package also has two lists used by the editor palettes: types.ts (default export: names of layout components) and relations.ts (default export: names of pure relations nodes).
Metadata
| Metadata | Interface | Shape |
| --- | --- | --- |
| Layout | LayoutComponentMetadata<TOptions> (@anglr/dynamic/layout) | {id, package, name, displayName?, scope?, options} – a tree, children are stored inside options |
| Relations | RelationsComponentMetadata<TOptions>[] (@anglr/dynamic/relations) | {id, package, name, displayName?, scope?, relationsOptions, outputs?: [{outputName, inputs: [{id, inputName}]}]} |
| Relations in editor | RelationsNodeMetadata[] (@anglr/dynamic/relations-editor) | Relations metadata + nodeMetadata: {coordinates: {x, y}, scopeConfigurable, options} |
The relations runtime accepts RelationsNodeMetadata[] as well, the editor-only nodeMetadata is ignored there.
Loading pipeline
Items are loaded by a DynamicItemLoader. For a DynamicItemSource it:
- asks every registered
DynamicModuleProvider(tryToGet(source)) and takes the first module returned (an ES module fromimport()), - passes the module to
DynamicModuleDataExtractors, which read the exports (default,extensions, …) into an item definition, - validates the result and caches it by
package+name.
Packages plug into this pipeline only by registering their DynamicModuleProviders on multi tokens (LAYOUT_COMPONENTS_MODULE_PROVIDERS, RELATIONS_COMPONENTS_MODULE_PROVIDERS, …). The loaders themselves are created by the core features.
| Loader token | Providers token (multi) | Extractors token (multi) | Used by |
| --- | --- | --- | --- |
| LAYOUT_COMPONENTS_LOADER | LAYOUT_COMPONENTS_MODULE_PROVIDERS | LAYOUT_COMPONENTS_MODULE_DATA_EXTRACTORS | Layout renderer |
| LAYOUT_MODULE_TYPES_LOADER | LAYOUT_MODULE_TYPES_PROVIDERS | LAYOUT_MODULE_TYPES_DATA_EXTRACTORS | Layout editor palette (types.ts) |
| RELATIONS_COMPONENTS_LOADER | RELATIONS_COMPONENTS_MODULE_PROVIDERS | RELATIONS_COMPONENTS_MODULE_DATA_EXTRACTORS | Relations runtime (pure nodes) |
| RELATIONS_MODULE_TYPES_LOADER | RELATIONS_MODULE_TYPES_PROVIDERS | RELATIONS_MODULE_TYPES_DATA_EXTRACTORS | Relations editor palette (relations.ts) |
| RELATIONS_NODES_LOADER | RELATIONS_NODES_PROVIDERS | RELATIONS_NODES_DATA_EXTRACTORS | Relations editor nodes |
Runtime and editor scopes
provideDynamic() combines one or more core features with any number of features. Core features decide what the scope does: layout runtime, relations runtime, layout editor, relations editor. Features (like withBasicComponents()) contribute providers per scope type, and only the parts relevant for the enabled core features are used. That's why the same withBasicComponents() works on a runtime page and in an editor.
All services (renderer, relations processor, editor managers) are provided by provideDynamic(), not in root. Each component with provideDynamic() in its providers gets its own independent layout and relations.
Built-in packages
| Entry point / feature | Package name | Layout components | Relations nodes |
| --- | --- | --- | --- |
| @anglr/dynamic/basic-components withBasicComponents() | basic-components | block, button, gridPanel, htmlBlock, ifBlock, listBlock, stackPanel, templateBlock, textBlock, toggleButton | debounceValue, deconstruct, empty, firstNonNull, logicalAnd, logicalOr, match, merge, negation, state, syncValues, transformData, trigger, value |
| @anglr/dynamic/form withFormComponents() | form-components | formGroup, textField, numberField, textarea, checkbox, radio, select, datepicker, period | – |
| @anglr/dynamic/material-components withMaterialComponents() | material-components | textField, numberField, textarea, checkbox, radio, select, datepicker, period, expansionPanel, tabGroup | – |
| @anglr/dynamic/css-components withCssComponents() | css-components | styleBlock | – |
| @anglr/dynamic/handlebars-components withHandlebarsComponents() | handlebars-components | dataBlock | dataTemplate |
| @anglr/dynamic/rest-components withRestComponents() | rest-components | – | rest |
| @anglr/dynamic/tinymce-components withTinyMceComponents() | tinymce-components | richTextBlock | richTextSource |
| @anglr/dynamic/math-components withMathComponents() | math-components | – | add, subtract, multiply, divide, power, round |
| @anglr/dynamic/grid-components withGridComponents() | grid-components | dataTable, gridColumn, asyncDataLoader, syncDataLoader, basicPaging, previousNextPaging, dialogMetadataSelector, showMetadataSelectorButton | – |
Several layout components are also relations components with their own inputs and outputs, for example:
| Item | Relations inputs | Relations outputs |
| --- | --- | --- |
| basic-components/button | disabled | click |
| basic-components/toggleButton | disabled | toggle |
| basic-components/ifBlock | condition | – |
| basic-components/htmlBlock | content | – |
| basic-components/listBlock | data | datum, index, first, last (provided per rendered item by the scoped ListBlockRelations) |
| form fields (form-components, material-components) | value, disabled, required (select also values) | valueOutput |
Some packages are created by the features themselves: layout-components (layout components used as relations nodes), static-components (template components used as relations nodes), custom-components and custom-relations.
Providers and setup
provideDynamic
Signature: provideDynamic(coreFeatures: CoreDynamicFeature[]|CoreDynamicFeature, ...features: DynamicFeature[]): Provider[].
It returns a plain Provider[], usable in component providers (recommended) or in a route / application config. Typical combinations:
| Scope | Core feature | Typical features |
| --- | --- | --- |
| Render layout | withLayoutRuntime() | package features, withLayoutMetadataStorage() |
| Run relations only (template components) | withRelationsRuntime() | package features |
| Render layout with relations | withLayoutRelationsRuntime() | package features, withLayoutMetadataStorage(), withRelationsMetadataStorage(), withCustomComponents() |
| Layout editor | withLayoutEditor() | withPackageManager(), withEditorHotkeys(), withLayoutDefaultsOverride(), package features |
| Relations editor | withRelationsEditor() | withPackageManager() (required), withStaticComponents(), withRelationsDefaultsOverride(), package features |
| Relations editor for a layout | withLayoutRelationsEditor() | same as relations editor |
Core features
| Function | Entry point | Description |
| --- | --- | --- |
| withLayoutRuntime() | @anglr/dynamic/layout | Layout loader and default extractors, LayoutRenderer, default MetadataStorage for layouts |
| withLayoutEditor() | @anglr/dynamic/layout-editor | Includes layout runtime; adds editor renderer, palette loader, editor metadata extractors, LayoutEditorMetadataManager, non-persistent PackageManager, LAYOUT_HISTORY_MANAGER, EDITOR_METADATA_MANAGER |
| withRelationsRuntime() | @anglr/dynamic/relations | Relations loader, RelationsManager, RelationsComponentManager, RelationsProcessor, RelationsChangeDetector, CodeExecutor |
| withRelationsEditor() | @anglr/dynamic/relations-editor | Palette and node loaders, RelationsNodeManager, ScopeRegister, RELATIONS_HISTORY_MANAGER, EDITOR_METADATA_MANAGER |
| withLayoutRelationsRuntime() | @anglr/dynamic/layout-relations | Layout runtime + relations runtime |
| withLayoutRelationsEditor() | @anglr/dynamic/layout-relations | Layout runtime + relations editor; layout components of the layout passed to LayoutManager.setLayout() become relations nodes (package layout-components) |
Additional features
| Function | Entry point | Applies to | Description |
| --- | --- | --- | --- |
| withPackageManager(storageOrPackageManager) | @anglr/dynamic | layout editor, relations editor | string = storage name, the selection of used packages is persisted in PERMANENT_STORAGE; or a PackageManager type; or factoryFn(() => …) |
| withEditorHotkeys() | @anglr/dynamic | layout editor, relations editor | EditorHotkeys: ctrl+s save, ctrl+z undo, ctrl+y redo, del delete, ctrl+c/ctrl+x/ctrl+v copy/cut/paste |
| withLayoutMetadataStorage(type) | @anglr/dynamic/layout | layout runtime | MetadataStorage for layouts loaded by id (templateBlock, custom components) |
| withRelationsMetadataStorage(type) | @anglr/dynamic/relations | layout runtime | MetadataStorage for relations loaded by id; use it with a core feature that contains the layout runtime (withLayoutRelationsRuntime(), withLayoutRelationsEditor()) |
| withLayoutDefaultsOverride(type) | @anglr/dynamic/layout-editor | layout editor | DefaultsOverride for items dropped from the layout palette |
| withRelationsDefaultsOverride(type) | @anglr/dynamic/relations-editor | relations editor | DefaultsOverride for nodes dropped from the relations palette |
| withStaticComponents(register) | @anglr/dynamic/relations-editor | relations editor | Template components registered by a StaticComponentsRegister become nodes of package static-components |
| withCustomComponents(register?, ...refreshObservables) | @anglr/dynamic/layout-relations | layout runtime, layout editor, relations editor | Reusable stored layouts with relations as items of package custom-components; the register is used by the editors |
| withCustomRelations(register?, ...refreshObservables) | @anglr/dynamic/layout-relations | relations runtime, relations editor | Reusable stored relations as nodes of package custom-relations |
| withFormControlBuilder() | @anglr/dynamic/form | layout runtime | FormComponentControlBuilder that builds a FormGroup from layout metadata |
Package features
withBasicComponents(), withFormComponents(), withMaterialComponents(), withCssComponents(), withHandlebarsComponents(), withRestComponents(), withTinyMceComponents(), withMathComponents(), withGridComponents() – each registers the providers of one built-in package (see Built-in packages). Your own package gets its own feature in the same way, see Creating your own package.
Main DI tokens
Loader, module provider and extractor tokens are listed in Loading pipeline.
| Token | Entry point | Description |
| --- | --- | --- |
| EDITOR_METADATA_MANAGER | @anglr/dynamic | EditorMetadataManager of the current editor, getMetadata() returns the edited metadata |
| PACKAGE_SOURCES | @anglr/dynamic | Multi token of PackageSources, the packages offered by the package manager |
| SCOPE_ID | @anglr/dynamic | Id of the current scope |
| MONACO_EDITOR_RESOURCES_PATH | @anglr/dynamic | Path to Monaco editor resources, default 'monaco-editor/vs' |
| LAYOUT_METADATA_STORAGE | @anglr/dynamic/layout | MetadataStorage of layouts |
| LAYOUT_HISTORY_MANAGER | @anglr/dynamic/layout-editor | MetadataHistoryManager of the layout editor |
| LAYOUT_DEFAULTS_OVERRIDE | @anglr/dynamic/layout-editor | DefaultsOverride of the layout editor |
| LAYOUT_EDITOR_PROPERTY_TYPE_CONTROLS | @anglr/dynamic/layout-editor | Dictionary of property type name → property type control component |
| LAYOUT_EDITOR_PROPERTY_METADATA_PROPERTIES | @anglr/dynamic/layout-editor | Symbols under which property metadata decorators store their data |
| REFRESH_PALETTE_OBSERVABLES | @anglr/dynamic/layout-editor, @anglr/dynamic/relations-editor | Multi token, observables that refresh the palette; each entry point exports its own distinct token with this name (one for the layout editor palette, one for the relations editor palette) |
| RELATIONS_METADATA_STORAGE | @anglr/dynamic/relations | MetadataStorage of relations |
| RELATIONS_HISTORY_MANAGER | @anglr/dynamic/relations-editor | MetadataHistoryManager of the relations editor |
| RELATIONS_DEFAULTS_OVERRIDE | @anglr/dynamic/relations-editor | DefaultsOverride of the relations editor |
| FORM_COMPONENT_CONTROL | @anglr/dynamic/form | Parent form control (AbstractControl, usually a FormGroup) for form components |
| BUTTONS_PRESETS | @anglr/dynamic/basic-components | Button presets ({text?, cssClass}) offered in button properties |
Creating and using dynamic items
Using built-in items
- Add the package feature to
provideDynamic()(withBasicComponents(),withMaterialComponents(), …). - Reference items in metadata by
packageandnameand give every instance a uniqueid. - Render the layout with
*layoutComponentRendererand, when relations are used, pass the relations metadata toRelationsManager.setRelations(). - In editors, items show up in the palette once their package is used: either pass
[packages]to the editor or let the user select packages in the built-in package manager.
Files and naming conventions
Built-in packages follow these conventions, and a package of your own should follow them too. One folder per item, the folder name is the item name.
| File | Content |
| --- | --- |
| <name>.options.ts | Options interface: <Name>ComponentOptions (layout) or <Name>RelationsOptions (relations) |
| <name>.component.ts / .html | Layout component, extends LayoutComponentBase<Options> |
| <name>.relations.ts | Pure relations component, decorated with @PureRelationsComponent() |
| <name>.metadata.ts | Lazy loaders of editor metadata (DynamicMetadataLoader) |
| metadata/<name>.layoutMetadata.ts | LayoutEditorMetadataDescriptor – palette info, properties, default options, children handling |
| metadata/<name>.model.ts | Model for the properties editor, decorated with @LayoutProperty* |
| metadata/<name>.relationsMetadata.ts | RelationsEditorMetadataDescriptor – palette info, default options, node component |
| node/<name>Node.component.ts / .html | Node displayed in the relations editor, extends RelationsNodeBase |
| misc/…, extensions/… | Item specific properties controls, extensions |
| type.ts | Module loaded by the loader: default export + optional extensions / childExtensions |
Package level files:
| File | Content |
| --- | --- |
| types.ts | Default export: names of layout components shown in the layout palette |
| relations.ts | Default export: names of pure relations nodes shown in the relations palette |
| services/* | Three DynamicModuleProviders: items (type.ts of an item), types (types.ts), relations (relations.ts) |
| features.ts | with<Package>() function returning a DynamicFeature |
| index.ts | Public exports: options interfaces and the feature |
Creating items in your own project
The complete, recommended setup is shown in ⭐ Creating your own package of dynamic items. In short:
- Create the item folder with options, component (or relations class), editor metadata and
type.ts. - List the item in
types.ts(layout components) orrelations.ts(pure relations nodes). - Write three
DynamicModuleProviders that return modules for your package name andnullfor any other package. - Write a
with…()function returning aDynamicFeaturethat registers the providers for each scope, plusprovideStaticPackageSource('<package>')for the editors. - Add the feature to
provideDynamic()next to the built-in ones.
Layout components that are also relations components don't belong to relations.ts; in the relations editor they appear as nodes of the layout-components package.
Customizing properties of dynamic items
Options interface and model
The options interface (<name>.options.ts) is the runtime contract: it describes metadata.options of a layout component, available as this.options in the component. The properties editor works with a model: a class implementing the options interface whose properties carry editor metadata. The model is registered in metaInfo.optionsMetadata.propertiesMetadata of the item's LayoutEditorMetadataDescriptor together with the controls that edit it:
optionsMetadata:
{
propertiesMetadata:
[
{
modelType: ComponentStylingModel,
propertiesControls:
[
getPropertiesControl(ComponentStylingPropertiesControlComponent),
],
},
{
modelType: CounterModel,
propertiesControls:
[
genericPropertiesControlFor<CounterModel>(['label', 'step']),
],
},
],
},LayoutEditorOptionsMetadata also has childPropertiesMetadata – properties shown on the children of a container, used for options read by child extensions (like flex of a stack panel child).
import {DefaultKnownPropertyTypes, LayoutPropertyDescription, LayoutPropertyName, LayoutPropertyType} from '@anglr/dynamic/layout-editor';
import {mapValuesToThis} from '@jscrpt/common';
import {CounterComponentOptions} from '../counter.options';
/**
* Counter model for properties editor
*/
export class CounterModel implements CounterComponentOptions
{
//######################### public properties #########################
/**
* @inheritdoc
*/
@LayoutPropertyName('Label')
@LayoutPropertyDescription('Label displayed next to current count')
@LayoutPropertyType<DefaultKnownPropertyTypes>('inputString')
public label: string|undefined|null = null;
/**
* @inheritdoc
*/
@LayoutPropertyName('Step')
@LayoutPropertyDescription('Value added to count on each click')
@LayoutPropertyType<DefaultKnownPropertyTypes>('inputNumber')
public step: number|undefined|null = null;
//######################### constructor #########################
constructor(value: CounterComponentOptions|undefined|null)
{
mapValuesToThis.bind(this)(value);
}
}The default value of a model property is only the default of the properties editor. A newly dropped component gets metaInfo.defaultOptions, an existing component keeps its own options.
Property metadata decorators
All from @anglr/dynamic/layout-editor:
| Decorator | Description |
| --- | --- |
| @LayoutPropertyName(name) | Label of the property in the properties editor |
| @LayoutPropertyDescription(description) | Description shown as a tooltip |
| @LayoutPropertyType<TType>(type) | Property type, selects the control that edits the value (see below) |
| @LayoutPropertyValues<TType>(values) | Values offered by selectValue |
| @LayoutPropertyObject(type, metadataSymbols) | Nested object with its own property metadata |
A property without @LayoutPropertyType isn't rendered by the generic properties control. That's useful for options edited by a custom control (see Custom property editor) or for children (content).
Property types
Property types available by default (registered in LAYOUT_EDITOR_PROPERTY_TYPE_CONTROLS):
| Type | Control |
| --- | --- |
| inputString | Text input (InputStringComponent) |
| textarea | Multi-line text (TextareaComponent) |
| inputNumber | Number input (InputNumberComponent) |
| inputBoolean | Checkbox (InputBooleanComponent) |
| selectValue | Select of @LayoutPropertyValues (SelectValueComponent) |
Properties controls
A properties control is one block of the properties editor. It's referenced by a getter in propertiesControls:
| Getter | Description |
| --- | --- |
| genericPropertiesControlFor<TModel>(properties) | Renders listed properties of the model, each by its property type |
| getPropertiesControl(type) | Uses any component implementing PropertiesControl (built-in ComponentStylingPropertiesControlComponent edits CSS class, margin and padding) |
| codePropertiesControlFor<TModel>(property, languageModel) | Edits one property in a Monaco code editor dialog (language models CssLanguageModel, HtmlLanguageModel, JsonLanguageModel, HandlebarsLanguageModel, TypescriptLanguageModel) |
Default options
- Layout:
metaInfo.defaultOptionsofLayoutEditorMetadataInfo– options of a component dropped from the palette. - Relations:
metaInfo.defaultOptionsofRelationsEditorMetadataInfo–relationsOptionsof a node dropped from the palette. - Per application: an implementation of
DefaultsOverride(getOptions(packageName, name, defaultOptions),getDisplayName(packageName, name, displayName?)) registered withwithLayoutDefaultsOverride()/withRelationsDefaultsOverride()changes defaults of any item, including built-in ones. See Overriding defaults.
Custom property editors
- Custom properties control – a component extending
PropertiesControlBase<TOptions>(implementsPropertiesControl). It gets theform(aFormGroupbuilt from the model),optionsandpropertiesMetadata; any value set intoformis applied to the component and recorded in history. Register it withgetPropertiesControl(MyControlComponent). See Custom property editor. - Custom property type – a component extending
PropertyTypeControlBase<TValue>(implementsPropertyTypeControl, withcontrol: FormControlandvalues). ProvideLAYOUT_EDITOR_PROPERTY_TYPE_CONTROLSwith a dictionary that contains the default controls (exportedInputStringComponent,InputBooleanComponent,SelectValueComponent,TextareaComponent,InputNumberComponent) plus your own type name. The token isn't multi, so the provided dictionary replaces the default one.
Layout
Layout metadata
Layout is a tree of LayoutComponentMetadata. There's no generic children property: each container stores its children inside its options in its own shape (children: LayoutComponentMetadata[] for stackPanel, content: LayoutComponentMetadata for block, ifBlock or the infoCard sample). Options consumed by extensions are plain properties of the same options object:
| Options | Consumed by |
| --- | --- |
| cssClass, margin {top, right, bottom, left}, padding {top, right, bottom, left}, textStyling {fontSize, fontWeight} | ComponentStylingExtension (@anglr/dynamic/layout) |
| flex (on a child of stackPanel) | Child extension of stackPanel |
Ids must be unique within one rendered layout.
Rendering layout
LayoutComponentRendererDirective (selector [layoutComponentRenderer], also exported by DynamicLayoutModule) renders one metadata node and everything below it:
<ng-container *layoutComponentRenderer="metadata"/>| Input | Type | Description |
| --- | --- | --- |
| layoutComponentRenderer | LayoutComponentMetadata \| undefined \| null | Metadata to render; changing it re-renders, null removes the component |
| layoutComponentRendererCallback | Action1<unknown> | Called with the rendered item after the component is fully initialized |
| layoutComponentRendererProviders | Provider[] | Extra providers for the injector of the rendered component (micro syntax *layoutComponentRenderer="metadata; providers: formProviders") |
LayoutRenderer loads the component type, creates the component, applies extensions, sets options and calls dynamicOnChanges, dynamicOnInit, invalidateVisuals and dynamicAfterViewInit. Public members: renderingFinished (observable), hasComponent(id), hasRenderer(id), destroyRenderer(id), unregisterRenderer(id).
LayoutComponentBase
LayoutComponentBase<TOptions> (@anglr/dynamic/layout) implements the LayoutComponent contract. Options aren't Angular inputs: the renderer assigns options and calls the dynamic lifecycle methods, which call these overridable hooks:
| Hook | Called |
| --- | --- |
| onInit() | Once, when the component is initialized |
| onOptionsSet() | After onInit() and after every later change of options |
| afterInit() | After extensions are initialized |
| onOptionsChange() | On every change of options except the first |
| onChanges(changes) | On changes other than options – relations inputs arrive here |
| onDestroy() | When the component is destroyed |
Protected members: optionsSafe (throws if options are missing), element, extensionsOptions, changeDetector, componentElement, injector, logger. invalidateVisuals() runs change detection of the component. Rendered components are detached from Angular change detection, so call invalidateVisuals() after the component changes its own state (for example in a click handler).
Containers and children
A container renders its children with the same directive and tells the editor where the children are:
@DescendantsGetter<TOptions>(options => …)(@anglr/dynamic/layout-editor) on the component class returns the child metadata. It's used to walk the tree (component tree,LayoutComponentsIteratorService).LayoutEditorMetadataDescriptorhandles editing:addDescendant(metadata, options, index),removeDescendant(id, options),canDropMetadata(options),getChildrenContainer(element),isHorizontalDrop(options),customDragType(),customDropTypes().metaInfo.dragDisabledprevents dragging,metaInfo.scopedmarks a component that creates its own scope.
A single-child container is shown in Custom layout component with editable properties.
Extensions
An extension is a class attached to an item through extensions (the item itself) or childExtensions (every child of a container) in type.ts. It's created with the item metadata and gets the injector, host element, component instance and options. Base class DynamicItemExtensionBase<TOptions, TInstance> (@anglr/dynamic) with hooks onInit(), onOptionsChange(), onDestroy() and fields injector, element, options, instance, metadata.
| Extension | Entry point | Description |
| --- | --- | --- |
| ComponentStylingExtension | @anglr/dynamic/layout | Applies cssClass, margin, padding, textStyling to the host element |
| RelationsRegistrationExtension | @anglr/dynamic/relations | Registers a layout component in relations under its layout id |
Missing components
When a layout component can't be loaded, LayoutRendererOptions.missingTypeBehavior decides what happens: MissingTypeBehavior.ShowNotFound (default, renders a not found placeholder), MissingTypeBehavior.Ignore or MissingTypeBehavior.ThrowError. Provide an instance of LayoutRendererOptions (constructor argument missingTypeBehavior) to change it.
Layout editor
<layout-editor> (LayoutEditorComponent, needs withLayoutEditor()) contains the component tree, the palette (with search and package manager), the canvas and the properties editor.
| Input | Type | Description |
| --- | --- | --- |
| metadata | LayoutComponentMetadata \| undefined \| null | Root of the edited layout; setting it resets history |
| packages | string[] \| undefined \| null | Packages shown in the palette; when set, the package manager UI is hidden |
| whiteList | DynamicItemSource[] \| undefined \| null | Only these items of the listed packages are shown |
| blackList | DynamicItemSource[] \| undefined \| null | Items hidden from the palette |
The editor has no save output. Saving is up to the application:
- current metadata – inject
EDITOR_METADATA_MANAGERand callgetMetadata(), - history – inject
LAYOUT_HISTORY_MANAGER(MetadataHistoryManager):undo(),redo(),canUndo,canRedo,save()(marks current state as saved),saved,historyChange, - hotkeys – with
withEditorHotkeys()the editor handles undo/redo/delete/copy/cut/paste itself andEditorHotkeys.saveemits onctrl+s.
Without [packages], the palette shows the packages selected in the package manager. Use withPackageManager('STORAGE_NAME') to remember that selection. A full editor page is in the Layout editor sample.
Relations
How relations work
Relations are a directed graph. Each node has an id, inputs (plain public properties) and outputs (properties decorated with @DynamicOutput()). An edge connects an output of one node to an input of another. When an output value changes, it's assigned to all connected inputs, then the target's dynamicOnChanges(changes) and invalidateVisuals() are called.
Relations need withRelationsRuntime() (or withLayoutRelationsRuntime() for layouts) and the metadata set with RelationsManager.setRelations(relations) in the same injector scope.
Relations metadata
Edges are stored on the source node: outputs[].inputs[] = {id: <target node id>, inputName: <target property>}.
| Node | package | name | id |
| --- | --- | --- | --- |
| Layout component | 'layout-components' | layout id | layout id |
| Pure relations node | package of the node | item name | any unique id |
| Static (template) component | 'static-components' | relations id of the component | relations id of the component |
relationsOptions are passed to relationsOptions of the node. A full example is in Layout with relations.
Data propagation
| Mechanism | Description |
| --- | --- |
| @DynamicOutput() | Default: changes are collected by RelationsChangeDetector and delivered asynchronously in one batch; all inputs of a target changed in a batch arrive in one dynamicOnChanges call |
| @DynamicOutput({sync: true}) | Value is transferred immediately when assigned |
| @DynamicOutput({skipInit: true}) | No initial transfer when relations are initialized, only real changes propagate (events like click) |
| Initial transfer | When relations are (re)initialized, outputs that were assigned at least once send their current value; the order in which components register doesn't matter |
| Equality check | A transfer is skipped when the new value is strictly equal to the previous one |
| RelationsChangeDetectorOptions(detectionInSingleRun) | Default true; with false, changes made during a run are delivered in the next run |
Kinds of relations nodes
| Kind | How | Sample |
| --- | --- | --- |
| Pure relations node | Plain class with @PureRelationsComponent(), implements RelationsComponent, constructor (injector: Injector), created by the runtime from metadata | Pure relations node |
| Layout + relations component | Layout component implementing RelationsComponent, with RelationsRegistrationExtension in type.ts; @PureRelationsComponent() must not be used on it | Component that is both layout and relations |
| Static component | Angular component in your own template that registers itself in RelationsComponentManager and RelationsProcessor | Static components in relations |
Optional members of RelationsComponent: dynamicOnChanges(changes) and relationsOnDestroy() (called for nodes created by the runtime when they are destroyed). Relations editor metadata (@RelationsEditorMetadata(loader), RelationsEditorMetadataDescriptor with metaInfo and nodeDefinition) makes a node available in the relations editor. The node component extends RelationsNodeBase and uses <relations-node-header>, <relation-node-input> and <relation-node-output>. The name of an input/output element must equal the runtime property name.
Relations editor
<relations-editor> (RelationsEditorComponent, needs withRelationsEditor() or withLayoutRelationsEditor() and withPackageManager()):
| Input | Type | Description |
| --- | --- | --- |
| metadata | RelationsNodeMetadata[] | Edited relations; setting it resets history |
| packages | string[] \| undefined \| null | Packages shown in the palette; when set, the package manager UI is hidden |
| whiteList | DynamicItemSource[] \| undefined \| null | Only these items of the listed packages are shown |
| blackList | DynamicItemSource[] \| undefined \| null | Items hidden from the palette |
Read the result with EDITOR_METADATA_MANAGER.getMetadata(), history is available under RELATIONS_HISTORY_MANAGER. With withLayoutRelationsEditor(), pass the layout to LayoutManager.setLayout(layout) so its relations-capable components appear as nodes. See the Relations editor sample.
Relations debugger
@anglr/dynamic/relations-debugger is experimental. It records registrations and data transfers of the relations runtime and replays them step by step on a canvas (ShowRelationsDebuggerDirective – [showRelationsDebugger] with relationsDefinition). It's enabled by provideRelationsDebugger() (@anglr/dynamic/relations) together with provideRelationsDebuggerImplementation() (@anglr/dynamic/relations-debugger). @DebugData({inputs, outputs}) describes endpoints of a node for the debugger.
Extensibility
| Extension point | What you can do | How to register |
| --- | --- | --- |
| DynamicModuleProvider | Load items of your own package, or from any other source (generated, remote) | Multi tokens LAYOUT_COMPONENTS_MODULE_PROVIDERS, LAYOUT_MODULE_TYPES_PROVIDERS, RELATIONS_COMPONENTS_MODULE_PROVIDERS, RELATIONS_MODULE_TYPES_PROVIDERS, RELATIONS_NODES_PROVIDERS, usually from a DynamicFeature |
| DynamicFeature | Bundle providers per scope (layoutRuntime, layoutEditor, relationsRuntime, relationsEditor, each {prependProviders, providers}) | Pass to provideDynamic() |
| DynamicModuleDataExtractor, DynamicModuleDataExtractorFn | Support other export conventions of item modules (built-in fns defaultExportExtractor, extensionsExportsExtractor) | Multi tokens *_DATA_EXTRACTORS |
| DynamicItemLoader | Replace the whole loading of a kind of items | Tokens LAYOUT_COMPONENTS_LOADER, RELATIONS_COMPONENTS_LOADER, LAYOUT_MODULE_TYPES_LOADER, RELATIONS_MODULE_TYPES_LOADER, RELATIONS_NODES_LOADER |
| DynamicItemExtensionBase | Reusable behavior attached to items | extensions / childExtensions export of type.ts |
| PackageSource | Provide the list of available packages (packages, packagesChange, refresh()) | Multi token PACKAGE_SOURCES; provideStaticPackageSource(name) for a fixed package |
| PackageManager | Control which packages are used in editors | withPackageManager(storageName \| Type \| factoryFn(…)) |
| MetadataStorage<TMetadata> | Load layouts/relations by id (getMetadata(id)) for templateBlock and custom components | withLayoutMetadataStorage(), withRelationsMetadataStorage() |
| DefaultsOverride | Default options and display names of dropped items | withLayoutDefaultsOverride(), withRelationsDefaultsOverride() |
| MetadataHistoryManager | Undo/redo history of editors | Tokens LAYOUT_HISTORY_MANAGER, RELATIONS_HISTORY_MANAGER |
| LayoutRenderer | Override createComponent, postCreateComponent, postInitComponent | Provide your subclass as LayoutRenderer |
| LayoutRendererOptions | Behavior for missing components | Provide an instance |
| PropertiesControlBase | Custom block of the properties editor | getPropertiesControl(type) in propertiesControls |
| PropertyTypeControlBase | Custom property type | LAYOUT_EDITOR_PROPERTY_TYPE_CONTROLS |
| @LayoutEditorDesignerType(loader) | Render a different component for an item inside the layout editor | Decorator on the component class |
| StaticComponentsRegister | Template components as relations editor nodes | withStaticComponents() |
| CustomComponentsRegister, CustomRelationsRegister | Reusable stored layouts / relations | withCustomComponents(), withCustomRelations() |
| REFRESH_PALETTE_OBSERVABLES | Refresh the palette when your data change | Multi token, or the refresh arguments of withCustomComponents() / withCustomRelations() |
The full worked example of the main extension point – an own package with layout components, a layout + relations component and a pure relations node – is the ⭐ Creating your own package of dynamic items sample, together with the item samples that follow it.
Styling
Setup
@anglr/dynamic/styles exports:
| Member | Description |
| --- | --- |
| defineTheme($colors, $font) | Function, merges colors with the default theme |
| buildThemeColors($theme) | Mixin, emits --dynamic-* CSS custom properties |
| buildThemeCss | Mixin, emits CSS of the editors and built-in components (.btn variants, gap/margin/padding utilities, thin scrollbar) |
| buildTheme($theme) | Mixin, buildThemeColors($theme) + buildThemeCss |
A theme is defined from a theme file (here inside a @use … with (…) theme configuration of the application):
@use '@anglr/dynamic/styles/themes/dark' as dynamicTheme; $dynamicTheme: dynamicTheme.defineTheme(),Colors are emitted inside the theme selector of the application:
@use '@anglr/dynamic/styles' as dynamic;$dynamicTheme: null !default; @include dynamic.buildThemeColors($dynamicTheme);CSS is emitted once for the page:
@use '@anglr/dynamic/styles' as dynamic; @include dynamic.buildThemeCss;Themes
@anglr/dynamic/styles/themes/dark and @anglr/dynamic/styles/themes/light export defineTheme($colors: (), $font: 'Inter'). Pass a partial map to change colors, the keys follow the theme map (btnPrimary, btnInfo, btnSuccess, btnDanger, btnIcon, formControl, scrollbar, dragPlaceholder, dropzoneOverlay, layoutDesigner, propertiesEditor, relationsCanvas, componentsPalette, componentsTree, componentsTreeItem, layoutEditorDragPreview, nodesPalette, relationNodeEndpoint, packageManager, notFoundNode, placeholder, contentOptions, relationsDebuggerVisualizer, relationsDebuggerTooltip, dataTableDesigner).
CSS custom properties
The most important variables (all emitted by buildThemeColors):
| Variable | Description |
| --- | --- |
| --dynamic-font-family | Font of editors |
| --dynamic-btn-primary-background, -foreground, -border | Primary button (also info, success, danger variants) |
| --dynamic-btn-icon-foreground | Icon buttons |
| --dynamic-form-control-foreground, -background, -border | Form controls |
| --dynamic-thin-scrollbar | Scrollbar color |
| --dynamic-drag-placeholder | Drop placeholder in layout editor |
| --dynamic-layoutDesigner-overlay-border | Border of selected/highlighted component in layout editor |
| --dynamic-layoutDesigner-title-background, -foreground | Title of selected component in layout editor |
| --dynamic-properties-editor-properties-main-background, -border | Properties editor panel |
| --dynamic-components-palette-editor-component-background, -border | Items of the layout palette |
| --dynamic-components-tree-background, -border | Component tree |
| --dynamic-relations-canvas-background | Relations editor canvas |
| --dynamic-relations-canvas-relations-node-header-background, -foreground | Header of relations nodes |
| --dynamic-relations-canvas-relations-node-content-background | Content of relations nodes |
| --dynamic-relation-node-endpoint-background | Input/output endpoints of nodes |
| --dynamic-nodes-palette-editor-component-background, -border | Items of the relations palette |
| --dynamic-placeholder-foreground, -background | Placeholders |
Samples
Each sample is a standalone component; data files (*.data.ts) contain the metadata that an application usually loads from a server. Samples are listed from the most important. The layout from Quick Start is the simplest one.
Layout with relations
Connect layout components with relations: the toggle button shows and hides details (toggle → ifBlock.condition) and, through the built-in negation node, enables the save button (toggle → negation.condition, negatedCondition → button.disabled). Layout components are referenced in relations with package layout-components and their layout id. Every input target has its own entry, even without outputs.
import {Component, ChangeDetectionStrategy, inject} from '@angular/core';
import {provideDynamic} from '@anglr/dynamic';
import {LayoutComponentMetadata, LayoutComponentRendererDirective} from '@anglr/dynamic/layout';
import {RelationsManager} from '@anglr/dynamic/relations';
import {withLayoutRelationsRuntime} from '@anglr/dynamic/layout-relations';
import {withBasicComponents} from '@anglr/dynamic/basic-components';
import {layoutRelationsLayout, layoutRelationsRelations} from './layoutRelations.data';
/**
* Renders layout and connects its components using relations
*/
@Component(
{
selector: 'layout-relations-sample',
templateUrl: 'layoutRelations.component.html',
imports:
[
LayoutComponentRendererDirective,
],
providers:
[
provideDynamic(withLayoutRelationsRuntime(),
withBasicComponents()),
],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class LayoutRelationsComponent
{
//######################### protected properties - template bindings #########################
/**
* Layout metadata to be rendered
*/
protected metadata: LayoutComponentMetadata = layoutRelationsLayout;
//######################### constructor #########################
constructor()
{
inject(RelationsManager).setRelations(layoutRelationsRelations);
}
}<ng-container *layoutComponentRenderer="metadata"/>import {LayoutComponentMetadata} from '@anglr/dynamic/layout';
import {RelationsComponentMetadata} from '@anglr/dynamic/relations';
/**
* Layout metadata of layout with relations sample
*/
export const layoutRelationsLayout: LayoutComponentMetadata =
{
id: 'stackPanel-root',
displayName: 'root',
package: 'basic-components',
name: 'stackPanel',
options:
{
children:
[
{
id: 'toggleButton-show',
displayName: 'show details',
package: 'basic-components',
name: 'toggleButton',
options:
{
onText: 'Hide details',
offText: 'Show details',
state: false,
buttonCssClass: 'btn btn-primary',
},
},
{
id: 'ifBlock-details',
displayName: 'details',
package: 'basic-components',
name: 'ifBlock',
options:
{
condition: false,
content:
{
id: 'textBlock-details',
package: 'basic-components',
name: 'textBlock',
options:
{
text: 'Details are visible only when toggle button is on',
},
},
},
},
{
id: 'button-save',
displayName: 'save',
package: 'basic-components',
name: 'button',
options:
{
text: 'Save (enabled when details are visible)',
buttonCssClass: 'btn btn-primary',
type: 'button',
disabled: true,
},
},
],
},
};
/**
* Relations metadata of layout with relations sample, layout components are referenced by their id
*/
export const layoutRelationsRelations: RelationsComponentMetadata[] =
[
{
id: 'toggleButton-show',
package: 'layout-components',
name: 'toggleButton-show',
relationsOptions: null,
outputs:
[
{
outputName: 'toggle',
inputs:
[
{id: 'ifBlock-details', inputName: 'condition'},
{id: 'negation-save', inputName: 'condition'},
],
},
],
},
{
id: 'negation-save',
package: 'basic-components',
name: 'negation',
relationsOptions: null,
outputs:
[
{
outputName: 'negatedCondition',
inputs:
[
{id: 'button-save', inputName: 'disabled'},
],
},
],
},
{
id: 'ifBlock-details',
package: 'layout-components',
name: 'ifBlock-details',
relationsOptions: null,
},
{
id: 'button-save',
package: 'layout