The @jsonforms/angular package provides a service for managing form state, renderers, and data updates in Angular applications.
The core service for managing JSON Forms state in Angular. This service handles state management, renderer registration, and data updates.
import { JsonFormsAngularService } from '@jsonforms/angular';
Initialization
init()
Initializes the service with the initial form state.
init(
initialState?: JsonFormsSubStates,
middleware?: Middleware
): void
Initial state containing core data, schema, UI schema, renderers, and configuration.Structure:{
core: {
data: any;
schema: JsonSchema;
uischema: UISchemaElement;
validationMode?: ValidationMode;
additionalErrors?: ErrorObject[];
};
renderers?: JsonFormsRendererRegistryEntry[];
cells?: JsonFormsCellRendererRegistryEntry[];
config?: any;
i18n?: JsonFormsI18nState;
uischemas?: { tester: UISchemaTester; uischema: UISchemaElement }[];
readonly?: boolean;
}
middleware
Middleware
default:"defaultMiddleware"
Custom middleware function for intercepting state updates.
State Access
$state
Observable that emits the current JSON Forms state.
get $state(): Observable<JsonFormsState>
Example:
this.jsonformsService.$state.subscribe(state => {
console.log('Current data:', state.jsonforms.core.data);
console.log('Errors:', state.jsonforms.core.errors);
});
getState()
Returns a deep clone of the current state.
getState(): JsonFormsState
getConfig()
Returns a deep clone of the current configuration.
getLocale()
Returns the current locale string.
getLocale(): string | undefined
Data Management
setData()
Updates the form data.
The new data to set. Should match the structure defined by the JSON Schema.
Example:
this.jsonformsService.setData({
name: 'John Doe',
age: 30
});
updateCore()
Dispatches a core action to update the state.
updateCore<T extends CoreActions>(coreAction: T): T
A core action from @jsonforms/core Actions.
Example:
import { Actions } from '@jsonforms/core';
this.jsonformsService.updateCore(
Actions.update('name', () => 'Jane Doe')
);
updateCoreState()
Updates multiple core state properties at once.
updateCoreState(
data: any | typeof USE_STATE_VALUE,
schema: JsonSchema | typeof USE_STATE_VALUE,
uischema: UISchemaElement | typeof USE_STATE_VALUE,
ajv: Ajv | typeof USE_STATE_VALUE,
validationMode: ValidationMode | typeof USE_STATE_VALUE,
additionalErrors: ErrorObject[] | typeof USE_STATE_VALUE
): void
Use USE_STATE_VALUE to keep the current value for a parameter.
Schema Management
setSchema()
Updates the JSON Schema.
setSchema(schema: JsonSchema | undefined): void
The new JSON Schema. If undefined, a schema will be generated from the data.
setUiSchema()
Updates the UI Schema.
setUiSchema(uischema: UISchemaElement | undefined): void
The new UI Schema. If undefined, a default UI schema will be generated.
setUiSchemas()
Sets the UI schema registry for dynamic schema resolution.
setUiSchemas(
uischemas: { tester: UISchemaTester; uischema: UISchemaElement }[]
): void
Renderer Management
addRenderer()
Registers a single renderer.
addRenderer(
renderer: JsonFormsBaseRenderer<UISchemaElement>,
tester: RankedTester
): void
renderer
JsonFormsBaseRenderer<UISchemaElement>
required
The renderer component class.
Function that determines if this renderer can handle a given UI schema element.
Example:
this.jsonformsService.addRenderer(
MyCustomRenderer,
rankWith(3, scopeEndsWith('myField'))
);
setRenderers()
Sets the entire renderer registry, replacing existing renderers.
setRenderers(renderers: JsonFormsRendererRegistryEntry[]): void
renderers
JsonFormsRendererRegistryEntry[]
required
Array of renderer registrations.
Example:
import { angularMaterialRenderers } from '@jsonforms/angular-material';
this.jsonformsService.setRenderers(angularMaterialRenderers);
removeRenderer()
Removes a renderer by its tester function.
removeRenderer(tester: RankedTester): void
The tester function of the renderer to remove.
Configuration
updateConfig()
Updates the global configuration.
updateConfig<T extends SetConfigAction>(setConfigAction: T): T
A config action created with Actions.setConfig().
Example:
import { Actions } from '@jsonforms/core';
this.jsonformsService.updateConfig(
Actions.setConfig({
restrict: true,
trim: false,
showUnfocusedDescription: true
})
);
Internationalization
updateI18n()
Updates internationalization settings.
updateI18n<T extends I18nActions>(i18nAction: T): T
An i18n action created with Actions.updateI18n().
Example:
import { Actions } from '@jsonforms/core';
this.jsonformsService.updateI18n(
Actions.updateI18n(
'de-DE',
(key, defaultMessage) => translate(key) || defaultMessage,
(error, translate) => translate(error.message)
)
);
setLocale()
Sets the current locale.
setLocale(locale: string): void
The locale string (e.g., ‘en-US’, ‘de-DE’).
Other Methods
setReadonly()
Sets whether the entire form is read-only.
setReadonly(readonly: boolean): void
Whether the form should be read-only.
updateValidationMode()
Updates the validation mode.
updateValidationMode(validationMode: ValidationMode): void
The validation mode: 'ValidateAndShow', 'ValidateAndHide', or 'NoValidation'.
setMiddleware()
Sets custom middleware for state updates.
setMiddleware(middleware: Middleware): void
Custom middleware function.
refresh()
Forces a refresh of the state observable.
Deprecated Methods
The following methods are deprecated. Use the recommended alternatives:
registerRenderer() - Use addRenderer() instead
registerRenderers() - Use setRenderers() instead
unregisterRenderer() - Use removeRenderer() instead
updateUiSchema() - Use setUiSchemas() instead
Usage Example
Here’s a complete example of using the service in a component:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { JsonFormsAngularService } from '@jsonforms/angular';
import { Actions } from '@jsonforms/core';
import { angularMaterialRenderers } from '@jsonforms/angular-material';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-dynamic-form',
template: `
<button (click)="updateData()">Update Data</button>
<button (click)="toggleReadonly()">Toggle Readonly</button>
<pre>{{ currentData | json }}</pre>
`,
providers: [JsonFormsAngularService]
})
export class DynamicFormComponent implements OnInit, OnDestroy {
private subscription: Subscription;
currentData: any = {};
isReadonly = false;
constructor(private jsonformsService: JsonFormsAngularService) {}
ngOnInit() {
// Initialize the service
this.jsonformsService.init({
core: {
data: { name: '', email: '' },
schema: {
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string', format: 'email' }
},
required: ['name', 'email']
},
uischema: {
type: 'VerticalLayout',
elements: [
{ type: 'Control', scope: '#/properties/name' },
{ type: 'Control', scope: '#/properties/email' }
]
}
},
renderers: angularMaterialRenderers
});
// Subscribe to state changes
this.subscription = this.jsonformsService.$state.subscribe(state => {
this.currentData = state.jsonforms.core.data;
});
}
updateData() {
this.jsonformsService.updateCore(
Actions.update('name', () => 'John Doe')
);
}
toggleReadonly() {
this.isReadonly = !this.isReadonly;
this.jsonformsService.setReadonly(this.isReadonly);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
The JsonFormsAngularService is automatically provided by the JsonForms component. You only need to manually provide it if you’re managing state independently.