[ Web Proxy ]
URL:
Viewing: https://docs.kitbase.dev/sdks/angular [Back]  [Original]

Angular SDK | Kitbase
Skip to content
Main Navigation HomeQuick StartWeb AnalyticsSDKsDashboardChangelog
Menu
Return to top
Sidebar Navigation

Getting Started

AI Visibility

Site Audit

Keyword Research

Workflows

On this page
    Copy page

    Angular Integration

    The @kitbase/analytics-angular package wraps the core SDK with Angular-native dependency injection via provideKitbaseAnalytics() and an injectable KitbaseAnalyticsService.

    Standalone-First

    The package uses provideKitbaseAnalytics() which works with standalone Angular applications (Angular 14+). No NgModule is required.

    Installation

    pnpmnpmyarn
    bash
    pnpm add @kitbase/analytics-angular
    bash
    npm install @kitbase/analytics-angular
    bash
    yarn add @kitbase/analytics-angular

    Setup

    Register the provider in your application config. The SDK initializes eagerly at bootstrap so auto-tracking is active immediately.

    typescript
    // app.config.ts
    import { ApplicationConfig } from '@angular/core';
    import { provideKitbaseAnalytics } from '@kitbase/analytics-angular';
    
    export const appConfig: ApplicationConfig = {
      providers: [
        provideKitbaseAnalytics({
          sdkKey: 'YOUR_SDK_KEY',
        }),
      ],
    };

    INFO

    SDK keys are public and safe to commit to source control. They are used only to identify which project to send traffic to and do not grant access to your data.

    Configuration Options

    All options beyond sdkKey are optional. Sensible defaults are applied automatically.

    typescript
    provideKitbaseAnalytics({
      sdkKey: 'YOUR_SDK_KEY',
      debug: false,
    
      analytics: {
        autoTrackPageViews: true,       // Tracks pushState / popstate navigations
        autoTrackClicks: true,          // Tracks clicks on interactive elements
        autoTrackOutboundLinks: true,   // Tracks clicks on external links
        autoTrackScrollDepth: true,     // Tracks max scroll depth per page
        autoTrackVisibility: true,      // Tracks element visibility via data attributes
        autoTrackWebVitals: false,      // Requires 'web-vitals' package
        autoDetectFrustration: true,    // Detects rage clicks and dead clicks
      },
    
      offline: {
        enabled: false,
        maxQueueSize: 1000,
        flushInterval: 30000,           // 30 seconds
        flushBatchSize: 50,
        maxRetries: 3,
      },
    
      botDetection: {
        enabled: true,
      },
    });

    Auto-Tracking

    Everything below is enabled by default no manual wiring needed. The SDK patches history.pushState and listens for popstate, so Angular Router navigations are captured automatically.

    FeatureConfig KeyWhat It Tracks
    Page viewsautoTrackPageViewsInitial load + SPA navigations (pushState / popstate)
    ClicksautoTrackClicksClicks on buttons, links, inputs, and other interactive elements
    Outbound linksautoTrackOutboundLinksClicks on links to external domains
    Scroll depthautoTrackScrollDepthMaximum scroll percentage per page
    Element visibilityautoTrackVisibilityTime an element is visible in the viewport (via data attributes)
    Frustration signalsautoDetectFrustrationRage clicks (3+ rapid clicks) and dead clicks (no DOM change)
    Web VitalsautoTrackWebVitalsLCP, CLS, INP, FCP, TTFB (requires web-vitals package)

    Data Attributes

    Use data attributes for declarative tracking without writing TypeScript.

    Click tracking fires a custom event when the element is clicked:

    html
    <button data-kb-track-click="CTA Clicked"
            data-kb-click-channel="marketing">
      Sign Up
    </button>

    Visibility tracking measures how long an element is visible in the viewport:

    html
    <div data-kb-track-visibility="Pricing Section Viewed"
         data-kb-visibility-channel="marketing"
         data-kb-visibility-threshold="0.75">
      Pricing details...
    </div>
    AttributeDescription
    data-kb-track-clickEvent name fired on click
    data-kb-click-channelChannel for the click event (default: 'engagement')
    data-kb-track-visibilityEvent name fired when element leaves viewport
    data-kb-visibility-channelChannel for the visibility event (default: 'engagement')
    data-kb-visibility-thresholdIntersectionObserver threshold 01 (default: 0.5)

    Using the Service

    Inject KitbaseAnalyticsService into any component or service.

    typescript
    import { Component, inject } from '@angular/core';
    import { KitbaseAnalyticsService } from '@kitbase/analytics-angular';
    
    @Component({ selector: 'app-checkout', templateUrl: './checkout.component.html' })
    export class CheckoutComponent {
      private kitbase = inject(KitbaseAnalyticsService);
    
      async onPurchase(order: Order): Promise<void> {
        await this.kitbase.track({
          channel: 'payments',
          event: 'Purchase Completed',
          tags: { amount: order.total, items: order.items.length },
        });
    
        await this.kitbase.trackRevenue({
          amount: order.total,
          currency: order.currency,
        });
      }
    }

    API Reference

    Event Tracking

    typescript
    // Custom event
    kitbase.track({ channel: 'ui', event: 'Button Clicked', tags: { location: 'header' } });
    
    // Page view (usually automatic  call manually only if needed)
    kitbase.trackPageView({ path: '/custom-path' });
    
    // Revenue
    kitbase.trackRevenue({ amount: 1999, currency: 'USD', tags: { plan: 'premium' } });
    
    // Outbound link
    kitbase.trackOutboundLink({ url: 'https://example.com', text: 'Visit Example' });

    User Identity

    typescript
    // Identify after login
    await kitbase.identify({
      userId: 'user_123',
      traits: { email: 'user@example.com', plan: 'premium' },
    });
    
    // Get current user ID
    const id = kitbase.getUserId(); // string | null
    
    // Clear identity on logout
    kitbase.reset();

    See Identify Users for more on how identity resolution works.

    Super Properties

    Attach properties to every subsequent event automatically.

    typescript
    // Merge properties into all future events
    kitbase.register({ app_version: '2.4.1', platform: 'web' });
    
    // Set only if not already registered
    kitbase.registerOnce({ initial_referrer: document.referrer });
    
    // Remove a single property
    kitbase.unregister('platform');
    
    // Read or clear all
    kitbase.getSuperProperties();
    kitbase.clearSuperProperties();

    Time Events

    Measure duration between two points.

    typescript
    // Start a timer
    kitbase.timeEvent('Checkout Flow');
    
    // ... user completes checkout ...
    
    // The next track() call for this event name automatically includes the duration
    await kitbase.track({ channel: 'conversions', event: 'Checkout Flow' });
    
    // Other helpers
    kitbase.getTimedEvents();                 // string[]
    kitbase.getEventDuration('Checkout Flow'); // number | null (ms)
    kitbase.cancelTimeEvent('Checkout Flow');  // stop without tracking

    Plugins

    typescript
    kitbase.use(myPlugin);        // Register a plugin
    kitbase.getPlugins();         // string[]  active plugin names

    Utilities

    typescript
    kitbase.setDebugMode(true);   // Enable console logging
    kitbase.isDebugMode();        // boolean
    kitbase.shutdown();           // Cleanup and stop all tracking
    kitbase.getInstance();        // Access the underlying core SDK instance

    Next Steps

    Pager

    Released under the MIT License.


    Web Proxy Viewer  |  New URL  |  Original Page