A/B Smartly - Angular SDK
The A/B Smartly Angular SDK is compatible with Angular 16 and later. It supports both standalone components and NgModule-based architectures. The SDK wraps the @absmartly/javascript-sdk and provides Angular-native services, components, and directives for seamless integration with Angular's dependency injection system.
The examples below use Angular's built-in control flow (@if), which requires Angular 17 or later. On Angular 16, use the equivalent *ngIf (for example <p *ngIf="absmartly.loading()">Loading experiments...</p>).
npm install @absmartly/angular-sdk --savePlease follow the installation instructions before trying the following code.
This example assumes an Api Key, an Application, and an Environment have been created in the A/B Smartly web console.
For applications using standalone components, use the provideABSmartly function in your application config:
import { provideABSmartly } from "@absmartly/angular-sdk";
export const appConfig = {
providers: [
provideABSmartly({
endpoint: "https://your-company.absmartly.io/v1",
apiKey: "YOUR-API-KEY",
environment: "development",
application: "website",
units: { session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8" },
}),
],
};For applications using the traditional NgModule architecture, import ABSmartlyModule.forRoot():
import { NgModule } from "@angular/core";
import { ABSmartlyModule } from "@absmartly/angular-sdk";
@NgModule({
imports: [
ABSmartlyModule.forRoot({
endpoint: "https://your-company.absmartly.io/v1",
apiKey: "YOUR-API-KEY",
environment: "development",
application: "website",
units: { session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8" },
}),
],
})
export class AppModule {}provideABSmartly({
endpoint: "https://your-company.absmartly.io/v1",
apiKey: "YOUR-API-KEY",
environment: "development",
application: "website",
units: { session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8" },
timeout: 5000,
retries: 3,
publishDelay: 100,
refreshPeriod: 0,
});You can provide a custom event logger:
provideABSmartly({
endpoint: "https://your-company.absmartly.io/v1",
apiKey: "YOUR-API-KEY",
environment: "development",
application: "website",
units: { session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8" },
eventLogger: (context, eventName, data) => {
console.log(`ABSmartly event: ${eventName}`, data);
},
});SDK Options
| Config | Type | Required? | Default | Description |
|---|---|---|---|---|
| endpoint | string |
✅ | undefined |
The URL to your API endpoint. Most commonly "https://your-company.absmartly.io/v1" |
| apiKey | string |
✅ | undefined |
Your API key which can be found on the Web Console. |
| environment | string |
✅ | undefined |
The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. |
| application | string |
✅ | undefined |
The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. |
| units | Record<string, string> |
✅ | undefined |
A map of unit types to unit identifiers (e.g., { session_id: "abc123" }). |
| timeout | number |
❌ | 3000 |
HTTP connection timeout in milliseconds. |
| retries | number |
❌ | 5 |
Maximum number of retry attempts for failed HTTP requests. |
| publishDelay | number |
❌ | -1 |
Delay in milliseconds before publishing events. Use -1 to publish immediately. |
| refreshPeriod | number |
❌ | 0 |
Period in milliseconds for automatic context refresh. Use 0 to disable. |
| eventLogger | (context, eventName, data) => void |
❌ | undefined |
Callback to handle SDK events (ready, exposure, goal, etc.) |
The Angular SDK automatically creates a context during service initialization using the units provided in the configuration. The ABSmartlyService exposes reactive signals to track the context state.
import { Component, inject } from "@angular/core";
import { ABSmartlyService } from "@absmartly/angular-sdk";
@Component({
selector: "app-root",
template: `
@if (absmartly.loading()) {
<p>Loading experiments...</p>
} @else if (absmartly.failed()) {
<p>Failed to load experiments</p>
} @else {
<app-main-content />
}
`,
})
export class AppComponent {
absmartly = inject(ABSmartlyService);
}You can inject a pre-existing context using the ABSMARTLY_CONTEXT injection token, avoiding a round-trip to the collector:
import { ABSMARTLY_CONTEXT } from "@absmartly/angular-sdk";
// Provide an existing context obtained from server-side rendering or another source
providers: [{ provide: ABSMARTLY_CONTEXT, useValue: existingContext }];const absmartly = inject(ABSmartlyService);
await absmartly.refresh();You can add additional units to a context by calling the setUnit() method. This is useful when a user logs in and you want to associate the new identity with the context. Note that you cannot override an already set unit type.
absmartly.setUnit("db_user_id", "1000013");When you need to create a new context with different units (for example, after a user logs out and a new user logs in), use the resetContext() method. This finalizes the current context and creates a new one with pre-fetched data:
await absmartly.resetContext(
{ session_id: "new-session-id", db_user_id: "2000042" },
{ publishDelay: 100, refreshPeriod: 0 },
);import { Component, inject } from "@angular/core";
import { ABSmartlyService } from "@absmartly/angular-sdk";
@Component({
selector: "app-product",
template: `
@if (treatment === 0) {
<app-product-control />
} @else {
<app-product-treatment />
}
`,
})
export class ProductComponent {
private absmartly = inject(ABSmartlyService);
treatment = this.absmartly.treatment("exp_test_experiment");
}The TreatmentComponent provides declarative, template-driven variant rendering:
import { Component } from "@angular/core";
import {
TreatmentComponent,
TreatmentVariantDirective,
} from "@absmartly/angular-sdk";
@Component({
selector: "app-experiment",
standalone: true,
imports: [TreatmentComponent, TreatmentVariantDirective],
template: `
<abs-treatment name="exp_button_color">
<ng-template absTreatmentVariant="loading">
<p>Loading...</p>
</ng-template>
<ng-template [absTreatmentVariant]="0">
<button class="btn-blue">Control: Blue Button</button>
</ng-template>
<ng-template [absTreatmentVariant]="1">
<button class="btn-green">Treatment: Green Button</button>
</ng-template>
<ng-template absTreatmentVariant="error">
<button class="btn-blue">Fallback: Blue Button</button>
</ng-template>
</abs-treatment>
`,
})
export class ExperimentComponent {}Variant directives support matching by number, string, letter (A=0, B=1, C=2...), or the special values "loading", "error", and "default".
The TreatmentDirective provides the variant and variables as a template context:
import { Component } from "@angular/core";
import { TreatmentDirective } from "@absmartly/angular-sdk";
@Component({
selector: "app-feature",
standalone: true,
imports: [TreatmentDirective],
template: `
<ng-container
*absTreatment="
'exp_test_experiment';
let variant;
let variables = variables;
let loading = loading
"
>
@if (loading) {
<p>Loading...</p>
} @else if (variant === 0) {
<p>Control group</p>
} @else {
<p>Treatment group</p>
}
</ng-container>
`,
})
export class FeatureComponent {}const buttonColor = absmartly.variableValue("button_color", "blue");Although generally not recommended, it is sometimes necessary to peek at a treatment or variable without triggering an exposure. The peek() and peekVariableValue() methods serve this purpose.
const treatment = absmartly.peek("exp_test_experiment");const buttonColor = absmartly.peekVariableValue("button_color", "blue");The TreatmentComponent also supports peeking via the peek input:
<abs-treatment name="exp_test_experiment" [peek]="true">
<!-- variant templates -->
</abs-treatment>During development, for example, it is useful to force a treatment for an experiment. This can be achieved with the override() method.
absmartly.override("exp_test_experiment", 1);absmartly.attribute("user_agent", navigator.userAgent);
absmartly.attributes({
customer_age: "new_customer",
url: window.location.href,
});absmartly.customAssignment("exp_test_experiment", 1);const fieldValue = absmartly.customFieldValue(
"exp_test_experiment",
"my_field",
);
const fieldKeys = absmartly.customFieldKeys();
const fieldType = absmartly.customFieldValueType(
"exp_test_experiment",
"my_field",
);Goals are created in the A/B Smartly web console.
absmartly.track("payment", {
item_count: 1,
total_amount: 1999.99,
});Sometimes it is necessary to ensure all events have been published to the A/B Smartly collector, before proceeding. You can explicitly call the publish() method.
await absmartly.publish();The finalize() method will ensure all events have been published to the A/B Smartly collector, like publish(), and will also "seal" the context, throwing an error if any method that could generate an event is called. The context is also automatically finalized when the ABSmartlyService is destroyed (via Angular's OnDestroy lifecycle).
await absmartly.finalize();absmartly.isReady();
absmartly.isFailed();
absmartly.isFinalized();
absmartly.pending();
absmartly.experiments();
absmartly.data();The ABSmartlyService exposes Angular signals for reactive state management:
absmartly.ready(); // Signal<boolean> - true when context is ready
absmartly.failed(); // Signal<boolean> - true when context initialization failed
absmartly.loading(); // Signal<boolean> - true while context is initializing
absmartly.error(); // Signal<Error | null> - error if initialization failedFor advanced use cases, you can access the underlying JavaScript SDK context and SDK instances directly:
const context = absmartly.getContext();
const sdk = absmartly.getSDK();The A/B Smartly SDK can be instantiated with an event logger used for all contexts. The event logger receives the context, event name, and event data.
provideABSmartly({
endpoint: "https://your-company.absmartly.io/v1",
apiKey: "YOUR-API-KEY",
environment: "development",
application: "website",
units: { session_id: "abc123" },
eventLogger: (context, eventName, data) => {
switch (eventName) {
case "exposure":
console.log("Exposed to experiment:", (data as { name: string }).name);
break;
case "goal":
console.log("Goal tracked:", (data as { name: string }).name);
break;
case "error":
console.error("SDK error:", data);
break;
case "ready":
case "refresh":
case "publish":
case "finalize":
break;
}
},
});Event Types
| Event | When | Data |
|---|---|---|
error |
Context receives an error |
Error object |
ready |
Context turns ready |
ContextData used to initialize |
refresh |
Context.refresh() method succeeds |
ContextData used to refresh |
publish |
Context.publish() method succeeds |
PublishEvent sent to collector |
exposure |
Context.treatment() succeeds on first exposure |
Exposure enqueued for publishing |
goal |
Context.track() method succeeds |
GoalAchievement enqueued for publishing |
finalize |
Context.finalize() method succeeds the first time |
null |
Releases are published to npm by .github/workflows/publish.yml when a v* tag is pushed. The tag must equal the package.json version (v1.0.0 for 1.0.0), otherwise the workflow fails before publishing.
- Bump
versioninpackage.json(andpackage-lock.json) in a PR and merge it. - Tag the merge commit and push the tag:
git tag v1.0.0 && git push origin v1.0.0.
The workflow runs the format check, tests and build, checks that the version is not on npm yet, then runs npm publish --provenance --access public. A release whose major is lower than the current latest on npm is published under latest-v<major> (for example latest-v1) so it never becomes latest. Prereleases go to alpha, beta, rc or next. A release lower than the version its dist-tag points to on npm now is refused. A release lower than latest in the same major, or lower than a release already published under its latest-v<major>, is refused.
Releases run one at a time, never in parallel. Tags pushed together are queued in roughly the order their runs start, which GitHub does not guarantee, so push tags one at a time when order matters. A release that runs after a higher one in the same major is refused rather than published. The release check reads npm metadata that the registry may cache for up to five minutes, so wait a few minutes between releases of different majors (for example a 2.0.0 and a 1.x patch).
To rehearse a release, run the workflow manually (Actions, Publish, Run workflow) with dry_run checked (the default). It runs every step and ends with npm publish --dry-run. Run from a v* tag, it also checks the tag against the version. Run from a branch, there is no tag to check. A dry run never receives NPM_TOKEN, so it does not exercise the token fallback, and it fails if the version is already on npm.
Authentication uses npm Trusted Publishing (OIDC) from the npm environment. Until a trusted publisher is configured on npmjs.com, which npm only allows once the package exists, the workflow falls back to the NPM_TOKEN secret.
A/B Smartly is the leading provider of state-of-the-art, on-premises, full-stack experimentation platforms for engineering and product teams that want to confidently deploy features as fast as they can develop them. A/B Smartly's real-time analytics helps engineering and product teams ensure that new features will improve the customer experience without breaking or degrading performance and/or business metrics.