Skip to content

API service reference

NgxViewBuilderApiService is a root-provided façade. Inject it anywhere in the host app to read, mutate, and observe the active view. This page lists every public method; events are listed separately in the Events reference.

ts
import { inject } from '@angular/core';
import { NgxViewBuilderApiService } from 'ngx-view-builder';

private api = inject(NgxViewBuilderApiService);

Scoped instances

When several runtime views render at once (e.g. a view inside a dialog), each gets a scoped child API. Data calls on the root service (setData, getData, setValue, table settings/filters) automatically delegate to the most recently created scoped child, so host code usually just talks to the root instance.

Structure & settings

MethodDescription
getStructure(): IStructure | nullReturns the current view definition as plain JSON (the source snapshot if one was captured, otherwise serialized from the live model).
getStructureModel(): IStructure | nullReturns the live structure model (signal-based class instances) instead of plain JSON.
setStructure(structure: IStructure): voidReplaces the whole view: rebuilds the model, syncs the builder, applies runtime-variable definitions, and re-runs init rules.
updateStructure(updater: (s: IStructure) => void): booleanMutates the structure in place and notifies/rebuilds. Changes flow into Undo history and structureChanged.
getSettings(): IStructure['settings'] | nullCopy of the view-wide settings object.
getSetting(key: string): unknownOne setting by key; supports nested paths ('header.title').
setSetting(key: string, value: unknown): booleanSets one setting (nested paths supported). No-op when the value is already equal.
patchSettings(patch: Record<string, unknown>): booleanSets several settings at once; keys may be nested paths.
replaceSettings(settings): booleanReplaces the settings object wholesale.
updateSettings(updater: (settings) => void): booleanMutates settings via callback.
notifyStructureChanged(): voidEmits onStructureChanged manually (rarely needed — mutation methods call it for you).
captureStructureSource(structure): voidStores a structure snapshot used as the mutable source for updateStructure/setSetting. Called automatically by setStructure.
clearCapturedStructureSource(): voidDrops the captured snapshot.
markPristine(): voidResets the dirty flag (e.g. right after saving).
isDirty(): booleanWhether form data changed since load / last markPristine().
ts
api.updateStructure((s) => {
  s.settings.header = { ...s.settings.header, title: 'Client onboarding' };
});
api.markPristine();

Data & values

MethodDescription
getData(): Record<string, unknown>Current form data snapshot.
setData(data): voidReplaces the form data.
setElementsData(data): voidMerges several values into the current data (partial update).
setValue(dataPath, value): Promise<void>Sets one value by data path ('addresses[0].city'), running the same change pipeline as user input (expressions, dependencies, events).
setElementValue(elementDataPath, value): Promise<void>Alias of setValue targeted at an element's data path.
getElementValue(elementDataPath): unknownReads a value by element data path.
setElementErrors(nameOrPath, errors: string[]): booleanAttaches external error messages to an element (e.g. server-side validation).
clearElementErrors(nameOrPath): booleanRemoves external errors from an element.
getElementErrors(nameOrPath): string[]Current external errors of an element.
ts
await api.setValue('client.country', 'LT');
api.setElementErrors('email', ['This e-mail is already registered']);

Element lookup & manipulation

All lookup methods accept an element name, data path, or schema path.

MethodDescription
getElement(nameOrPath): unknownRaw element model (untyped).
getElementModel(nameOrPath): ElementBaseModel | nullTyped element model.
getElementByDataPath(dataPath) / getElementBySchemaPath(schemaPath)Lookup by a specific path kind.
getElementLookup(nameOrPath): INgxViewBuilderElementLookupResult | nullFull lookup record: name, paths, type, id, testId, model, and DOM node.
getRenderedElements(): INgxViewBuilderElementLookupResult[]Lookup records for everything currently rendered.
getElementName(nameOrPath) / getElementDataPath(...) / getElementSchemaPath(...) / getElementType(...) / getElementId(...) / getElementTestId(...)Convenience accessors for individual lookup fields.
getElementProperty(nameOrPath, propertyKey): unknownReads one element property ('hidden', 'label', …).
setElementProperty(nameOrPath, propertyKey, value): booleanSets one element property and re-renders.
setElementProperties(nameOrPath, props: Record<string, unknown>): booleanSets several properties at once.
updateElement(nameOrPath, updater: (el) => void): booleanMutates the element model via callback.
refreshElement(nameOrPath): booleanForces the element to re-render.
ts
api.setElementProperty('email', 'disabled', true);
api.updateElement('summaryPanel', (el: any) => { el.title = 'Order summary'; });

Render root & DOM access

MethodDescription
registerRenderRoot(root: HTMLElement | ShadowRoot | null): voidRegisters the root node views render into (the runtime component does this for you). Also hosts toast styles.
getRenderRoot(): HTMLElement | ShadowRoot | nullThe registered render root.
getElementDom(nameOrPath): HTMLElement | nullDOM node of a rendered element.
getElementDomById(id) / getElementDomByTestId(testId)DOM lookup by element id / test id.
queryRenderDom(selector): HTMLElement | nullquerySelector scoped to the render root.
queryRenderDomAll(selector): HTMLElement[]querySelectorAll scoped to the render root.

Validation, completion & lifecycle

MethodDescription
validateData(formJson, dataJson, options?): Promise<INgxViewBuilderValidationEvent>Headless validation: builds the structure, applies data, evaluates expressions and validators, and returns { isValid, issues[] } — no UI needed. See Headless validation.
showToast(payload: INgxViewBuilderToastPayload): voidShows a runtime toast (title, message, variant, position, autoHideMs, icon…).
notifyValidationResult(isValid, issues): voidEmits onValidated/onValidating and fires the validated platform trigger. Called by the runtime after UI validation.
notifyComplete(isValid, data, issues): voidEmits onComplete and the completed trigger. Called on Submit.
notifySaveRequested(source?): voidEmits onSaveRequested (source: 'header' | 'api') — a programmatic "Save" click.
notifyBeforeRender(tab) / notifyRender(tab) / notifyAfterRender(tab)Emit the render-phase events and matching beforeLoad/onLoad/afterLoad triggers. The builder/runtime call these; hosts rarely need to.
notifyTabChanged(tab): voidAnnounces that the builder tab changed (emits onTabChanged).
notifyCurrentPageChanged(pageIndex, pageName): voidAnnounces a page switch (emits onCurrentPageChanged + pageChanged trigger).
notifyDialogClosed(pageIndex, pageName, dialogTitle?, reason?): voidAnnounces a dialog-mode close (emits onDialogClosed + dialogClosed trigger).
ts
const result = await api.validateData(structureJson, dataJson);
if (!result.isValid) console.table(result.issues);

Data sources

MethodDescription
reloadDataSource(elementNameOrPath, dataSourceName?, runtimeContext?): Promise<unknown | null>Reloads the data source bound to an element (or a named source), with optional extra runtime context for placeholders.
reloadElementDataSource(elementNameOrPath, runtimeContext?): Promise<unknown | null>Shorthand: reload whatever source the element uses.
reloadElementsByDataSource(dataSourceName, runtimeContext?): Promise<unknown[]>Reloads every element consuming the named source (falls back to the raw source when nothing consumes it).
setDefaultDataSources(dataSources: IDataSource[], overwriteExisting?): voidInjects host-defined sources into the current structure so every view can use them (by name; existing names kept unless overwriteExisting).
setDataSourceTypeSettings(settings): voidEnables optional source types in the builder UI: { enableGraphql, enableWebsocket }.
getDataSourceTypeSettings(): INgxViewBuilderDataSourceTypeSettingsCurrent source-type switches.
ts
await api.reloadElementsByDataSource('loadClients');
api.setDefaultDataSources([{ name: 'countries', type: 'rest', url: '/api/countries' }]);

Runtime variables

MethodDescription
setRuntimeVariableDefinitions(definitions, replace = true): voidWrites the variable definitions into structure.settings and (re)binds them.
getRuntimeVariableDefinitions(): IRuntimeVariableDefinition[]Current definitions.
setRuntimeVariableContext(values, merge = true): voidSets the external context available as {__external.*} in expressions.
getRuntimeVariableContext(): Record<string, unknown>Current external context.
clearRuntimeVariableContext(): voidClears the external context.
configureRuntimeVariables({ mappings?, external?, mergeExternal? }): voidOne-call setup: definitions + external context.

Details: Runtime variables.

Language, locale & translations

MethodDescription
getLanguage(): stringActive content/UI language.
setLanguage(language): voidSwitches the language (UI dictionaries + structure settings.language; registers the language in localization if new).
resolveHostLanguage(options?): INgxViewBuilderResolvedLanguageResolves the best { language, locale } from document/system language against supportedLanguages with a fallbackLanguage.
applyHostLanguage(options?): INgxViewBuilderResolvedLanguageresolveHostLanguage + applies it (setLanguage, and setApplicationLocale unless applyLocale: false).
startLanguageSync(options?): INgxViewBuilderLanguageSyncHandleKeeps the view in sync with the host page language: watches <html lang> and the browser languagechange event. Returns { refresh, stop }.
setApplicationLocale(locale): voidOverrides the locale used for number/date formatting (e.g. 'de-DE'), independent of the UI language. Until called, formatting falls back to the structure's settings.language, then the visitor's browser locale.
getApplicationLocale(): stringThe explicitly-set application locale, or '' if setApplicationLocale was never called (formatting is still active via the fallback chain above).
setLocale(locale): voidConvenience: sets the locale in both the application locale service and structure settings.
setContentTranslations(translations, merge = true): voidAdds content translations ({ lt: { 'First name': 'Vardas' } }) into the structure's localization.
setUiDictionaries(dictionaries, merge = true): voidOverrides builder/runtime UI dictionaries (see UI translations).
setUiTranslations(dictionaries, merge = true): voidAlias of setUiDictionaries.
translateUi(key, fallback?): stringTranslates a UI dictionary key.
setPropertyHints(hints): voidOverrides the help texts shown next to builder properties.
setPropertyTypeHints(hints): voidOverrides the help texts for property types (text, options, validators…).
ts
const handle = api.startLanguageSync({
  supportedLanguages: ['en', 'lt'],
  fallbackLanguage: 'en',
});
// later: handle.stop();

Theme & CSS

MethodDescription
setThemeMode(theme: 'light' | 'dark'): voidSwitches light/dark mode.
getThemeMode(): 'light' | 'dark' | nullCurrent mode (null until first set).
setTheme(theme): voidAccepts either a mode string ('dark') or a CSS-variable map — one call for both cases.
setCustomTheme(theme): voidRegisters a custom theme: { mergeWithDefaults?, shared?, light?, dark? } variable maps. Re-applies variables for the active mode.
getCustomTheme(): INgxViewBuilderCustomThemeDefinition | nullCurrent custom theme.
setCssVariables(cssVariables): voidSets raw CSS custom properties (names are auto-prefixed with --).
getCssVariables(): Record<string, string>Currently applied variables.
setCustomCss(cssText): voidInjects a raw CSS string into the render scope.
getCustomCss(): stringCurrent custom CSS.
setCustomCssUrls(urls): voidLoads external stylesheets into the render scope.
getCustomCssUrls(): string[]Current stylesheet URLs.

Details: Theming & design tokens, Custom CSS.

Extensions & registration

Everything from provideNgxViewBuilderExtensions is also callable imperatively:

MethodDescription
registerExtensions(config): voidRegisters a whole extensions config (icons, dictionaries, elements, functions, properties…) at runtime.
registerExtensionsAsync(config): Promise<void>Same, but awaits async icon directories.
registerElementGroup(group): voidAdds a custom group to the elements sidebar.
registerCustomElement(definition): voidRegisters one custom element.
registerCustomElements(definitions): voidRegisters several custom elements.
registerElementProperties(type, properties, merge = true): voidAdds/overrides builder properties for one element type (custom properties).
registerElementPropertiesMap(map, merge = true): voidProperties for several types at once.
registerGlobalElementProperties(properties, merge = true): voidProperties added to every element type.
registerExpressionFunction(fn) / registerExpressionFunctions(fns)Adds custom expression functions to the expression language.
registerSvgIcon(name, svgMarkup, overwrite = true): booleanRegisters one inline SVG icon.
registerSvgIcons(icons, overwrite = true): string[]Registers a map of icons; returns the registered names.
clearRegisteredSvgIcons(): voidRemoves all registered SVG icons.
registerSvgIconDirectory(config): Promise<{ loaded, failed }>Loads a directory of .svg files by URL manifest.
registerSvgIconDirectories(configs): Promise<...[]>Several directories at once.
getTableHeaderCenterExtensions(): INgxViewBuilderCustomElementDefinition[]Custom elements flagged allowInTableHeader (usable in table header bars).
attachBuilderAdapter(adapter): voidInternal bridge between this service and the builder UI — the builder component attaches itself; hosts don't call this.

Templates & sidebar library

MethodDescription
getTemplates(): ITemplateDefinition[]Templates of the current structure.
setTemplates(templates, replace = true) / loadTemplates(...)Loads host-persisted templates into the builder (both names do the same; loadTemplates reads more naturally on startup).
upsertTemplate(template) / saveTemplate(template, previousCode?)Adds or updates one template (saveTemplate also handles renames via previousCode).
removeTemplate(name) / deleteTemplate(code)Deletes a template.
setTemplateActionMap(map): voidMaps template action('...') names to action handlers.
registerTemplateActionDataSource(functionName, dataSourceName): voidBinds a template function call (e.g. loadData(id)) to a data source.
setSidebarTemplates(templates, replace = true) / setSidebarGroups(groups, replace = true) / loadSidebarGroups(groups, replace = true)Loads saved element-library items (the reusable elements/groups panel in the sidebar).
saveSidebarGroup(group, previousCode?) / upsertSidebarGroup(group)Adds or updates a sidebar library item.
deleteSidebarGroup(code) / removeSidebarGroup(code)Deletes a sidebar library item.

Persistence pattern: listen to onTemplateSaved / onSidebarGroupSaved etc., store items wherever you want, and call loadTemplates / loadSidebarGroups on startup.

Tables

MethodDescription
setTableSettings(identifier, settings, options?): voidApplies column settings (visibility/order/width) to a table. options: tableName, elementName, source ('host' | 'localStorage' | 'dataSource' | 'user').
getTableSettings(identifier)Stored settings for a table.
requestTableSettings(tableName, elementName, currentSettings): voidFires onTableSettingsRequested so the host can supply persisted settings.
requestTableSettingsSave(tableName, elementName, settings): voidFires onTableSettingsSaveRequested so the host can persist settings.
setTableFilters(identifier, filters, options?): voidApplies active detailed-search filters. options.source: 'host' | 'user' | 'savedFilter'; may carry the applied savedFilter.
getTableFilters(identifier)Stored active filters.
setTableSavedFilters(identifier, filters, options?): voidSupplies the saved-filter list for a table.
getTableSavedFilters(identifier)Stored saved filters.
requestTableSavedFilters(tableName, elementName, currentFilters): voidFires onTableSavedFiltersRequested (host should respond with setTableSavedFilters).
requestTableSavedFilterSave(tableName, elementName, filter, currentFilters): voidFires onTableSavedFilterSaveRequested so the host can persist one saved filter.

Use together with the table events to persist per-user column layouts and saved filters.

Builder UI control

MethodDescription
switchToTab(tab): voidSwitches the builder to a tab ('editor', 'preview', 'jsonEditor', 'formSettings', 'translations', 'variables', or a plugin tab code).
requestTabChange(tab): voidEmits onTabChangeRequested — the builder decides whether to honour it (useful when the host wraps tab navigation).
setAiAssistantConfig(config): voidSets the AI assistant backend config at runtime ({ backendUrl }); emits onAiAssistantConfigChanged.
getAiAssistantConfig(): INgxViewBuilderAiAssistantConfigCurrent AI assistant config.